Search for a special string in the text and replace the contents from the array

Consider this text

$text = 'bla bla bla bla (=abc) bla bla bla bla (=var.var)';

There are 2 special meanings (=abc)and(=var.var)

I need to replace them with values ​​from this array:

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

Mainly inside the pattern (= [az.] +) (Characters az and period).

I need the result: bla bla bla bla *word1* bla bla bla bla *word2*(without *)

I tried it 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 on D: \ net \ test \ index.php on line 9

+3
source share
2 answers

Since the replacement string cannot be obtained from the contents of the match (it includes external data in $array, you need to use preg_replace_callback.

PHP 5.3 , ( ) create_function PHP.

$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);
+3

PHP 5.3:)

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

+2

All Articles