Jump to content

Archived

This topic is now archived and is closed to further replies.

DylanBlitz

replace help

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.