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

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