Jump to content

replace help


DylanBlitz

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.