Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to replace an url in a string

Status
Not open for further replies.

hos2

Programmer
Joined
May 6, 2002
Messages
418
Location
NL
who knows the easiest way to replace an url in a string so that it becomes an url when loaded again
Code:
so
bbla bla bla [URL unfurl="true"]http://www.mywebsite.com[/URL] blabla

translate to

bbla bla bla <a href=[URL unfurl="true"]http://www.mywebsite.com[/URL] >[URL unfurl="true"]http://www.mywebsite.com</a>[/URL] blabla

after the url it's possible to have a return or an space

does anybody know a neat way to do this ??
 
A regular expression should do it.

Something like:

Code:
<?php
$string = 'bbla bla bla [URL unfurl="true"]http://www.mywebsite.com[/URL] blabla
blablia bla blablabla bla ftp://ftp.foo.com/foo/bar/foo.txt bla';

print preg_replace ('/((http|ftp):\/\/([a-z0-1_.]+\/*)+)/i', '<a href=&quot;$1&quot;>$1</a>', $string);
?>

Will output:

[ignore]bbla bla bla <a href=&quot; blabla
blablia bla blablabla bla <a href=&quot;ftp://ftp.foo.com/foo/bar/foo.txt&quot;>ftp://ftp.foo.com/foo/bar/foo.txt</a> bla[/ignore]

Want the best answers? Ask the best questions: TANSTAAFL!!
 
ah that almost works perfect. only how do I prefent that it will double preg_replace a url if someone has quoted a message, the a href is already in the message and then the url must not be replaced anymore ??

ps when I tried it with the link of this topic it stopped at
??
 
hmmmm and images should be treated differently. now I remember why I let this problem rest for a long time :(

think I have to examine the preg_replace manual ;)
 
oops. In the part of the regular expression that reads:

[ignore][a-z0-1_.][/ignore]

Change it to read:

[ignore][a-z0-1_.-][/ignore]

That'll take care of the &quot;ending at the dash&quot; problem.


However, you didn't ask about text that was already in the right form. That's a lot trickier -- regular expressions are designed to describe what is there, not what isn't.

I'm going to have to think about that one a while.

Making it specific to images and leaving alone things already in tags is probably going to take handing preg_replace() some match and replace arrays.

Want the best answers? Ask the best questions: TANSTAAFL!!
 
ah I've found something on

that sounds helpfull

Code:
$txt = preg_replace( &quot;/(?<!<a href=\&quot;)((http|ftp)+(s)?:\/\/[^<>\s]+)/i&quot;, &quot;<a href=\&quot;\\0\&quot;>\\0</a>&quot;, $txt );


and now a way to exclude the imageslinks :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top