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. Link to comment https://forums.phpfreaks.com/topic/23847-displaying-an-array-in-a-regular-expression-string/ 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] Link to comment https://forums.phpfreaks.com/topic/23847-displaying-an-array-in-a-regular-expression-string/#findComment-108377 Share on other sites More sharing options...
Drahcir Posted October 13, 2006 Author Share Posted October 13, 2006 Superb, works like a charm. Thanks :) Link to comment https://forums.phpfreaks.com/topic/23847-displaying-an-array-in-a-regular-expression-string/#findComment-108475 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.