isopogon Posted November 19, 2006 Share Posted November 19, 2006 I'm trying to use ereg_replace to turn a string like:[code]http://www.server.com/link.html[This is a Caption][/code]into a string like:[code]<a href="http://www.server.com/link.html">This is a Caption</a>[/code]I started with:[code]// match protocol://address/path/$temp = ereg_replace("[a-zA-Z]+://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "<a href=\"\\0\">\\0</a>", $temp);// match www.something$temp = ereg_replace("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)([a-zA-Z0-9])", "\\1<a href=\"http://\\2\">\\3</a>", $temp);[/code]But can't figure out how to modify these to produce the result I want. Quote Link to comment Share on other sites More sharing options...
Nicklas Posted November 19, 2006 Share Posted November 19, 2006 [code=php:0]<?php$string = 'bla bla bla http://www.server.com/link.html[This is a Caption] bla bla bla';echo preg_replace('/(http:\/\/[^\s]+)\[(.*?)]/is', '<a href="\\1">\\2</a>', $string);?>[/code] Quote Link to comment Share on other sites More sharing options...
isopogon Posted November 19, 2006 Author Share Posted November 19, 2006 Thanks.What works beautifully :), but I realised I didn't ask my original question properly.The caption in the square brackets doesn't always exist. Sometimes it's just a plain URL. In this case, the URL will be the caption.How do I specify that second substring is optional, and to use the first substring for the caption if the second one doesn't exist?Examples:[code]http://server.com/file.html[Caption]http://anotherserver.com/file2.html... should produce...<a href="http://server.com/file.html">Caption</a><a href="http://anotherserver.com/file2.html">http://anotherserver.com/file2.html</a>[/code]Thanks again. Quote Link to comment Share on other sites More sharing options...
Nicklas Posted November 19, 2006 Share Posted November 19, 2006 Make a call-back function and check if the caption was matched, if not, return the url as the caption.ex:[code=php:0]<?phpfunction link_it($url, $desc) { // Use the URL if no caption was matched... if (!$desc) { $link = "<a href=\"$url\">$url</a>"; } else { $link = "<a href=\"$url\">$desc</a>"; } return $link;}$string = 'bla bla bla http://www.server.com/link.html[This is a Caption] bla bla bla';echo preg_replace('/(http:\/\/[^\s\[]+)(\[(.*?)])?/eis', 'link_it("\\1", "\\3")', $string);?>[/code] Quote Link to comment Share on other sites More sharing options...
isopogon Posted November 19, 2006 Author Share Posted November 19, 2006 Thanks ;DYou're an absolute legend :) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.