Search special-string in a text and replace with contents from array
Consider this text
$text = 'bla bla bla bla (=abc) bla bla bla bla (=var.var)';
There are 2 special values there (=abc)
and (=var.var)
I need to replace them with values from this array:
$array['abc']='word1';
$array['var.var']='word2';
Basically inside the pattern is (=[a-z.]+) (chars a-z and dot).
Result i need: bla bla bla bla *word1* bla bla bla bla *word2*
(without *)
I tried this with no luck
preg_replace('/\(=([a-z\.]+)\)/',"$array['\\1'开发者_Python百科]",$text);
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\net\test\index.php on line 9
Since you the replacement string cannot be derived from the contents of the match (it involves external data in $array
, you need to use preg_replace_callback
.
This example assumes PHP 5.3 for anonymous functions, but you can do the same (in a slightly more cumbersome way) with create_function
in any PHP version.
$text = 'bla bla bla bla (=abc) bla bla bla bla (=var.var)';
$array['abc']='word1';
$array['var.var']='word2';
$result = preg_replace_callback(
'/\(=([a-z\.]+)\)/',
function($matches) use($array) { return $array[$matches[1]]; },
$text);
The < PHP 5.3 solution :)
$text = 'bla bla bla bla (=abc) bla bla bla bla (=var.var)';
$text = preg_replace_callback('/\(=([\w.]+?)\)/', 'processMatches', $text);
function processMatches($matches) {
$array = array();
$array['abc']='word1';
$array['var.var']='word2';
return isset($array[$matches[1]]) ? $array[$matches[1]] : '';
}
var_dump($text); // string(43) "bla bla bla bla word1 bla bla bla bla word2"
CodePad.
精彩评论