douan7601 2016-09-14 04:42
浏览 14
已采纳

正则表达式没有按预期工作 - PHP preg_match_all

I have string which contains a variable in curly braces and I want to replace them with a value.

$text = 'Hi My Name is ##{Name}## and I am ##{Adjective}##';

preg_match_all('/{([^#]+)}/i', $text, $matches);
foreach ($matches[1] as $key => $value) {
    $text = str_replace('{' . $value . '}', 'SomeValue', $text);
}
print_r($matches[1]);
print_r(str_replace('##', '', $text));

OUTPUT

Array ( [0] => Name [1] => Adjective ) 
Hi My Name is SomeValue and I am SomeValue

But I am not able to handle deifferent variations of the string for example.

1. $text = 'Hi My Name is ##{Name}{Adjective}##'
2. $text = 'Hi My Name is ##{Name}and I am{Adjective}##'
3. $text = 'Hi My Name is ##{Name}, {Adjective}##'
4. $text = 'Hi My Name is ##{Name} {Adjective}##'

I would want the similar result in array output so that values can be replaced

 Array ( [0] => Name [1] => Adjective ) 

NOTE: I am able to ensure that '##' will always be present at the start and end of the curly braces, but not necessarily in between the braces e.g. point 1,2,3,4 above in example string.

  • 写回答

2条回答 默认 最新

  • dongxun1142 2016-09-14 05:25
    关注

    I'd recommend using preg_replace_callback with the pattern /\{(.+?)}/ and a callback like this

    $callback = function($matches) use (&$found) {
      $found[] = $matches[1];
      return 'SomeValue';
    };
    

    This will let you record the matches in the $found array while replacing the entire {Name}, {Adjective} with "SomeValue".

    $found = [];
    $newTxt = str_replace('##', '',
        preg_replace_callback('/\{(.+?)}/', $callback, $txt));
    

    Demo here ~ https://eval.in/641827

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器