Jump to content


Photo

replace help


  • Please log in to reply
1 reply to this topic

#1 DylanBlitz

DylanBlitz
  • Members
  • PipPipPip
  • Advanced Member
  • 99 posts
  • LocationOC Baby!

Posted 14 August 2006 - 01:48 AM

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.

$text = preg_replace("/\[url=(\W?)(.*?)(\W?)\](.*?)\[\/url\]/", '<a href="$2">$4</a>', $text);

works great if they do it like
[url=http://www.somesite.com[Click here&[/url]
but if they just do
[url]http://www.somesite.com[/url]
it doesn't work.

any clue what I need to do to fix it? Or should I go about it another way?

#2 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 14 August 2006 - 01:04 PM

This could be improved by looking for valid URL characters, instead of everything but ] or [.

<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>

Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users