嗨,我希望有人能帮忙,因为对正则表达式不太感兴趣。
得到一个脚本片段如下…

<?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}*

相反,我希望它能回来。
test message *{image=abc}* more text text text *{image=def}*

谢谢你的帮助。

最佳答案

使用non-greedy而不是.*?来生成regex.*

$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}*

关于php - 使用php preg_replace_callback-但替换整个字符串而不是每个子字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19387523/

10-09 06:53
查看更多