Turn URLs and @* into links
def link_urls_and_users s
#regexps
url = /( |^)http:\/\/([^\s]*\.[^\s]*)( |$)/
user = /@(\w+)/
#replace @usernames with links to that user
while s =~ user
s.sub! "@#{$1}", "<a href='http://twitter.com/#{$1}' >#{$1}</a>"
end
#replace urls with links
while s =~ url
name = $2
s.sub! /( |^)http:\/\/#{name}( |$)/, " <a href='http://#{name}' >#{name}</a> "
end
s
end
puts link_urls_and_users(tweet.text)
This works, so long as URLs are padded by spaces or are at the beginning and/or end of the tweet.
Turn Plain Text URLs into Active Links using PHP
You may wonder how it works. I'll try to explain how it should be done by various methods. We'll start first with how regex works and how it is used.
Regex - Regular expression
In computing, a regular expression (abbreviated regex or regexp) is a
sequence of characters that forms a search pattern, mainly for use in
pattern matching with strings, or string matching, i.e. "find and
replace"-like operations.
Basic Syntax
To use regular expressions first you need to learn the syntax. This syntax consists of a series of letters, numbers, dots, hyphens and special signs, which we can group together using different parentheses.
^ The circumflex symbol matches the beginning of the input string or line, although in some cases it can be omitted
$ Same as with the circumflex symbol, the dollar sign matches the end of the input string or line
. The period matches any single character
? It will match the preceding pattern zero or one times
+ It will match the preceding pattern one or more times
* It will match the preceding pattern zero or more times
| Boolean OR
- Used when describing a range of elements
() Groups pattern elements together
[] Matches any single character between the square brackets
{min, max} Used to match exact character counts, where min and max are integers
\d Matches any single digit
\D Matches any single non digit caharcter
\w Matches any alpha numeric character including underscore (_)
\W Matches any non alpha numeric character excluding the underscore character
\s Matches any single whitespace character
Brackets
Brackets []
have a special meaning when used in the context of regular expressions. They are used to find a range of characters.
[0-9] Matches any decimal digit from 0 through 9.
[a-z] Matches any character from lowercase a through lowercase z.
[A-Z] Matches any character from uppercase A through uppercase Z.
[a-Z] Matches any character from lowercase a through uppercase Z.
Examples
Let's look at how to use properly the operators. We will do this with an example of the word hello
.
/hello/ Matches the word hello
/^hello/ Matches hello at the start of a string. Possible matches are hello or helloworld, but not worldhello
/hello$/ Matches hello at the end of a string or line.
/he.o/ Matches any character between he and o. Possible matches are helo or heyo, but not hello
/he?llo/ Matches either hllo or hello
/hello+/ Matches hello one or more times. E.g. matches hello or hellohello
/he*llo/ Matches llo, hello or hehello, but not hellooo
/hello|world/ Matches either hello or world
/(A-Z)/ Using the hyphen character to denote a range, matches every uppercase character from A to Z. E.g. A, B, C…
/[abc]/ Matches any single character a, b or c
/abc{1}/ Matches precisely one c character after the characters ab. E.g. matches abc, but not abcc
/abc{1,}/ Matches one or more c character after the characters ab. E.g. matches abc or abcc
/abc{2,4}/ Matches between two and four c character after the characters ab. E.g. matches abcc, abccc or abcccc, but not abc
The most common
[^a-zA-Z] Matches any string not containing any of the characters ranging from a through z and A through Z.
p.p Matches any string containing p, followed by any character, in turn followed by another p.
^.{2}$ Matches any string containing exactly two characters.
<b>(.*)</b> Matches any string enclosed within <b> and </b>.
p(hp)* Matches any string containing a p followed by zero or more instances of the sequence hp.
Regex to match a URL
At first let's look how a URL is built. We only have a couple of options:
http://example.com/
https://example.com/
ftp://example.com/
www.example.com
user@example.com
127.0.0.1
http://example.com:8080/
http://
, https://
, ftp
, www
, mail
, ip
and port
.
Method 1 (1/10 points)
// Only mails
$match = preg_match('/[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)*\@[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)+/', $string, $array);
Method 2 (5/10 points)
// Without ports, www-s, ip-s and mails
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $text);
Method 3 (10/10 points)
/* Proposed by:
* Søren Løvborg
* http://stackoverflow.com/users/136796/soren-lovborg
*/
$rexProtocol = '(https?://)?';
$rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
$rexPort = '(:[0-9]{1,5})?';
$rexPath = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
function callback($match)
{
// Prepend http:// if no protocol specified
$completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
return '<a href="' . $completeUrl . '">'
. $match[2] . $match[3] . $match[4] . '</a>';
}
$text = preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&",
'callback', htmlspecialchars($text));
You can write your own ideas to my answer.
I am writing...
How to auto convert an url into a hyperlink when it is pasted
Autolink URL in ContentEditable Iframe
In this question i answered
so that when a user paste's a url in a richtextbox it automatically converts any link to hyperlink - here my richtextbox is not a div its an iframe
if your's is a div or any other you can get answer from these two questions
Autolink URL in contenteditable jQuery: Convert text URL to link as typing
here's the code
autoAppLink: function (Iframe) {
var saveSelection, restoreSelection;
if (window.getSelection && document.createRange) {
saveSelection = function (containerEl) {
var range = iframe[0].contentWindow.getSelection().getRangeAt(0);
var preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(containerEl);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
var start = preSelectionRange.toString().length;
return {
start: start,
end: start + range.toString().length
}
};
restoreSelection = function (containerEl, savedSel) {
var charIndex = 0, range = document.createRange();
range.setStart(containerEl, 0);
range.collapse(true);
var nodeStack = [containerEl], node, foundStart = false, stop = false;
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
range.setStart(node, savedSel.start - charIndex);
foundStart = true;
}
if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
range.setEnd(node, savedSel.end - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
var i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}
var sel = iframe[0].contentWindow.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
} else if (document.selection) {
saveSelection = function (containerEl) {
var selectedTextRange = document.selection.createRange();
var preSelectionTextRange = document.body.createTextRange();
preSelectionTextRange.moveToElementText(containerEl);
preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange);
var start = preSelectionTextRange.text.length;
return {
start: start,
end: start + selectedTextRange.text.length
}
};
restoreSelection = function (containerEl, savedSel) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(containerEl);
textRange.collapse(true);
textRange.moveEnd("character", savedSel.end);
textRange.moveStart("character", savedSel.start);
textRange.select();
};
}
function createLink(matchedTextNode) {
var el = document.createElement("a");
el.href = matchedTextNode.data;
el.target = "_blank";
el.appendChild(matchedTextNode);
return el;
}
function shouldLinkifyContents(el) {
return el.tagName != "A";
}
function surroundInElement(el, regex, surrounderCreateFunc, shouldSurroundFunc) {
var child = el.lastChild;
while (child) {
if (child.nodeType == 1 && shouldSurroundFunc(el)) {
surroundInElement(child, regex, createLink, shouldSurroundFunc);
} else if (child.nodeType == 3) {
surroundMatchingText(child, regex, surrounderCreateFunc);
}
child = child.previousSibling;
}
}
function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
var parent = textNode.parentNode;
var result, surroundingNode, matchedTextNode, matchLength, matchedText;
while (textNode && (result = regex.exec(textNode.data))) {
matchedTextNode = textNode.splitText(result.index);
matchedText = result[0];
matchLength = matchedText.length;
textNode = (matchedTextNode.length > matchLength) ?
matchedTextNode.splitText(matchLength) : null;
surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
parent.insertBefore(surroundingNode, matchedTextNode);
parent.removeChild(matchedTextNode);
}
}
var iframe = Iframe,
textbox = iframe.contents().find("body")[0];
var urlRegex = /http(s?):\/\/($|[^ ]+)/;
function updateLinks() {
var savedSelection = saveSelection(textbox);
surroundInElement(textbox, urlRegex, createLink, shouldLinkifyContents);
restoreSelection(textbox, savedSelection);
}
var $textbox = $(textbox);
$textbox.focus();
var keyTimer = null, keyDelay = 1000;
$textbox.keyup(function () {
if (keyTimer) {
window.clearTimeout(keyTimer);
}
keyTimer = window.setTimeout(function () {
updateLinks();
keyTimer = null;
}, keyDelay);
});
}
Rails turn URL string into hyperlink
for your reference link_to
the format is
link_to(body, url, html_options = {})
# url is a String; you can use URL helpers like
for your problem
<td><%= link_to link.url, "http://#{link.url}" %></td>
Related Topics
Marshal Ruby Hash with Default Proc - Remove the Default Proc
How to Enable Colors with Rspec When Using Jruby or Bundle Exec
Ruby Optionparser Empty Switch "-" Behavior
Get All Keys in Hash with Same Value
Fresh Install of Rails and Getting Openssl Errors: "Already Initialized Constant Openssl"
Behaviour of Array Bang Methods
How to Generate a Unique Request Id in Rails
Ruby Class Object Garbage Collection
How to Mock Super in Ruby Using Rspec
Webmock Simulate Failing API (No Internet, Timeout ++)
Catching Command-Line Errors Using %X
Should Gemfile.Lock Be Committed to Source Control on Windows
Require Ruby File Without .Rb Extension
Prepared Statements Already Exists