Drahcir Posted October 13, 2006 Share Posted October 13, 2006 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. Quote Link to comment Share on other sites More sharing options...
effigy Posted October 13, 2006 Share Posted October 13, 2006 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] Quote Link to comment Share on other sites More sharing options...
Drahcir Posted October 13, 2006 Author Share Posted October 13, 2006 Superb, works like a charm. Thanks :) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.