Jump to content


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


Displaying an array in a regular expression string

Recommended Posts

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...[code]$mainString = preg_replace("/\[url=(.{1})\](.*)\[\/url\]/", "<a href=\"javascript:navTo('".$theArray[$1]."')$2\"></a>", $mainString);[/code]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.

Share this post

Link to post
Share on other sites
The[tt] $1 [/tt] must be quoted. Use[tt] /e [/tt] or a callback:


$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] .

echo $mainString = preg_replace_callback(


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.