Jump to content

Displaying an array in a regular expression string


Drahcir

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.
The[tt] $1 [/tt] must be quoted. Use[tt] /e [/tt] or a callback:

[code]
<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>
[/code]

Archived

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

×
×
  • 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.