Jump to content


Photo

Displaying an array in a regular expression string


  • Please log in to reply
2 replies to this topic

#1 Drahcir

Drahcir
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 13 October 2006 - 01:30 PM

Hey all,

I'm trying to replace part of a string using regular expression, however I want the replacement to be gathered from an array. Something like...
$mainString = preg_replace("/\[url=(.{1})\](.*)\[\/url\]/", "<a href=\"javascript:navTo('".$theArray[$1]."')$2\"></a>", $mainString);
However I'm getting syntax errors. I assume the errors are because I'm trying to access one of the regex fields out of a regex replacement string?
Any ideas?

Thanks, Richard.

#2 effigy

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

Posted 13 October 2006 - 03:13 PM

The $1 must be quoted. Use /e or a callback:

<pre>
<?php

	$theArray = array ('www.phpfreaks.com' => 'result');
	$mainString = '[url=www.phpfreaks.com]text[/url]';
	
	function url_callback(&$matches) {
		global $theArray;
		return '<a href="javascript:navTo(\'' .
			$theArray['www.phpfreaks.com'] .
			'\')">' .
			$matches[2] .
			'</a>';
	}
	
	echo $mainString = preg_replace_callback(
		"%\[url=(.+?)\](.+?)\[/url\]%",
		'url_callback',
		$mainString
	);

?>
</pre>

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

#3 Drahcir

Drahcir
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 13 October 2006 - 05:22 PM

Superb, works like a charm. Thanks :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users