dsaf415212 2013-10-15 09:38
浏览 96
已采纳

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

Hi I hope someone can help, as not too hot on regular expressions.

Got a script snippet as follows..

<?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;

?>

However when i run it, it returns

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

Instead I want it to return..

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

Thanks for any help.

  • 写回答

2条回答 默认 最新

  • dongyun6229 2013-10-15 09:41
    关注

    Make your regex non-greedy by using .*? instead of .*:

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

    OUTPUT

    test message *{image=abc}* more text text text *{image=def}*
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部