在文本中搜索特殊字符串并替换为数组中的内容

问题描述:

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']",$text);

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D: et\test\index.php on line 9

考虑此文本 p>

  $ text ='bla bla bla  bla(= abc)bla bla bla bla(= var.var)'; 
  code>  pre> 
 
 

那里有2个特殊值(= abc) code >和(= var.var) code> p>

我需要用这个数组中的值替换它们: p>

  $ array ['abc'] ='word1'; 
 $ array ['var.var'] ='word2'; 
  code>  pre> 
 
 

基本上在模式中 是(= [az。] +)(字符az和点)。 p>

我需要的结果: bla bla bla bla * word1 * bla bla bla bla * word2 * 代码>(没有*) p>

我试了这个没有运气 p>

  preg_replace('/ \(=([az \。]  +)\)/',“$ array ['\\ 1']”,$ text); 
  code>  pre> 
 
 

解析错误:语法错误,意外T_ENCAPSED_AND_WHITESPACE,期待 第9行的D: et \ test \ index.php中的T_STRING或T_VARIABLE或T_NUM_STRING p> div>

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.