开发者

preg_replace pass match through function before replacing

开发者 https://www.devze.com 2022-12-25 01:19 出处:网络
This is what i want to do: $line = \'blabla translate(\"test\") blabla\'; $line = preg_replace(开发者_JS百科\"/(.*?)translate\\((.*?)\\)(.*?)/\",\"$1\".translate(\"$2\").\"$3\",$line);

This is what i want to do:

$line = 'blabla translate("test") blabla';
$line = preg_replace(开发者_JS百科"/(.*?)translate\((.*?)\)(.*?)/","$1".translate("$2")."$3",$line);

So the result should be that translate("test") is replaced with the translation of "test".

The problem is that translate("$2") passes the string "$2" to the translate function. So translate() tries to translate "$2" instead of "test".

Is there some way to pass the value of the match to a function before replacing?


preg_replace_callback is your friend

  function translate($m) {
     $x = process $m[1];
     return $x;
  }

  $line = preg_replace_callback("/translate\((.*?)\)/", 'translate', $line);


You can use the preg_replace_callback function as:

$line = 'blabla translate("test") blabla';
$line = preg_replace_callback("/(.*?)translate\((.*?)\)(.*?)/",fun,$line);

function fun($matches) {    
 return $matches[1].translate($matches[2]).$matches[3];    
}
0

精彩评论

暂无评论...
验证码 换一张
取 消