Forum Moderators: coopster

Message Too Old, No Replies

Making string replace function

         

wavesurf

11:38 am on Aug 13, 2004 (gmt 0)

10+ Year Member



I need to make a function that goes through a string checking for potential [url]...[/url] in the string. These strings needs to be changed to an actual <a href>...</a> string.

But I'm all lost. Does anyone have any tips on how to do this.

Thanks.

mattx17

4:12 pm on Aug 13, 2004 (gmt 0)

10+ Year Member



The best way to do it is using preg_replace (see [php.net...] ).

Example:

$Contents = "some string with a link [somesite.com ]";

$NewContents = preg_replace("/\[url\](.+?)\[\/url\]/i","<a href=\"$1\">$1</a>",$Contents);

Hope this helps!

wavesurf

7:22 pm on Aug 13, 2004 (gmt 0)

10+ Year Member



Thanks, that helped a lot.

However, do you know how to check the actual link string for syntax, because if the link string includes "http://" it works great, but if the link string goes straight to "www.something.com" the link that is generated is just added to the local path.

It would be a lot better if the function could take this into account.

Any ideas?

coopster

4:21 am on Aug 14, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Add an optional pattern search, something like this:

$Contents = "some string with a link http://www.example.com and try also a www.example.com if you want, ok?"; 
$NewContents = preg_replace("/\[url\](http:\/\/)?(.+?)\[\/url\]/i","<a href=\"http://$2\">$2</a>",$Contents);

Note we are now using the second subpattern as well as forcing the

http://
back into the replacement string.

wavesurf

8:42 am on Aug 14, 2004 (gmt 0)

10+ Year Member



Thanks a bunch for all the help. Now it works perfectly.

Does anyone have any good links as to how to learn more about the regular expression matches? From all of this, it seems like a good thing to have some more knowledge about.

Thanks again for all the help.

jatar_k

4:19 pm on Aug 14, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



there are two referenced in this thread
Learning PHP - Books, Tutorials and Online Resources [webmasterworld.com]
msg 4 and 5