Welcome Guest, Not a member yet? Register   Sign In
Need regex help to replace links in a string
#1

[eluser]ehicks727[/eluser]
I've got a string that I need to turn properly formatted urls into anchor text.

For example...

Code:
$string = "http://www.example.com"

turns into...

Code:
'<a href="http://www.example.com">http://www.example.com</a>'

I appreciate the help!! Thank you.
#2

[eluser]Dyllon[/eluser]
Code:
$string = "http://codeigniter.com";

echo preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $string);
#3

[eluser]ehicks727[/eluser]
Sweet! thanks, worked great.
#4

[eluser]danmontgomery[/eluser]
http://ellislab.com/codeigniter/user-gui...elper.html

Quote:auto_link()

Automatically turns URLs and email addresses contained in a string into links. Example:
$string = auto_link($string);

The second parameter determines whether URLs and emails are converted or just one or the other. Default behavior is both if the parameter is not specified. Email links are encoded as safe_mailto() as shown above.

Converts only URLs:
$string = auto_link($string, 'url');

Converts only Email addresses:
$string = auto_link($string, 'email');

The third parameter determines whether links are shown in a new window. The value can be TRUE or FALSE (boolean):
$string = auto_link($string, 'both', TRUE);
#5

[eluser]ehicks727[/eluser]
Ah, forgot about that helper. Thank you. That actually worked better (sorry Dyllon) because the regex above does not catch dashes in the url.
#6

[eluser]sophistry[/eluser]
i fixed auto_link() a few months back. there were a lot of problems with it.

this links to the second page of the discussion, but has the full code (linked onto pastebin because of EE's"loose" handling of entities (i.e., it mangled them).
http://ellislab.com/forums/viewthread/95384/P15/




Theme © iAndrew 2016 - Forum software by © MyBB