Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php preg_replace_回调-但替换整个字符串而不是每个子字符串_Php_Regex_Preg Replace - Fatal编程技术网

使用php preg_replace_回调-但替换整个字符串而不是每个子字符串

使用php preg_replace_回调-但替换整个字符串而不是每个子字符串,php,regex,preg-replace,Php,Regex,Preg Replace,嗨,我希望有人能帮上忙,因为正则表达式不太流行 得到一个脚本片段,如下所示 <?php $news="test message {image=abc} more text text text {image=def}"; $news=preg_replace_callback("/\{image=.*\}/i",function ($matches) { $field=$matches[0]; return "*".$field."*"; }, $news); echo $news

嗨,我希望有人能帮上忙,因为正则表达式不太流行

得到一个脚本片段,如下所示

<?php

$news="test message {image=abc} more text text text {image=def}";

$news=preg_replace_callback("/\{image=.*\}/i",function ($matches) { $field=$matches[0];  return "*".$field."*"; }, $news);


echo $news;

?>
相反,我希望它能回来

test message *{image=abc}* more text text text *{image=def}*

谢谢您的帮助。

使用
*?
而不是
*
,使您的正则表达式
不贪婪

$news = "test message {image=abc} more text text text {image=def}";
$news = preg_replace_callback("/\{image=.*?\}/i",function ($matches) { 
                 return "*".$matches[0]."*"; }, $news);

echo $news;
输出

test message *{image=abc}* more text text text *{image=def}*
为什么要回电话

$news = preg_replace("/(\{image=[^\}]+\})/i", "*$1*", $news);

就像anubhava的回答-非常感谢你的回答。。我离得很近,但到目前为止:-)你为什么使用第一组?你可以去掉括号,在替换中使用
$0
,不管怎样+1:)晚一天,少一美元。
$news = preg_replace("/(\{image=[^\}]+\})/i", "*$1*", $news);