DylanBlitz Posted August 14, 2006 Share Posted August 14, 2006 Ok, I'm bad with expressions. I have this that I pulled off php.net for replacing the text to include a url. I have a page that people can post msgs to. I want to automatically create links out of text so I used the bbcode style for them to specify if it's a url.[code]$text = preg_replace("/\[url=(\W?)(.*?)(\W?)\](.*?)\[\/url\]/", '<a href="$2">$4</a>', $text);[/code]works great if they do it like [code][url=http://www.somesite.com[Click here&[/url][/code]but if they just do [code][url]http://www.somesite.com[/url][/code] it doesn't work.any clue what I need to do to fix it? Or should I go about it another way? Link to comment https://forums.phpfreaks.com/topic/17459-replace-help/ Share on other sites More sharing options...
effigy Posted August 14, 2006 Share Posted August 14, 2006 This could be improved by looking for valid URL characters, instead of everything but ] or [.[code]<pre><?php $tests = array( '[url=http://www.somesite.com]Click here[/url]', '[url]http://www.somesite.com[/url]' ); function link_it ($matches) { ### Throw away the full match. array_shift($matches); $url = $matches[0] ? $matches[0] : $matches[1]; $text = $matches[1]; return "<a href=\"$url\">$text</a>"; } foreach ($tests as $test) { echo $test, '<br />'; echo preg_replace_callback("/ \[url # opening url (?:=([^]]+))? # optional =address \] # closing url ([^[]+) # content \[\/url\] # ending url /x", 'link_it', $test); echo '<br /><br />'; } ?></pre>[/code] Link to comment https://forums.phpfreaks.com/topic/17459-replace-help/#findComment-74451 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.