douhuanchi6586 2016-08-22 15:25
浏览 34
已采纳

正则表达式多次替换包围的单词

I'm trying to replace all " " in twig syntax when it's surrounded by "{%" and "%}" or "{{" and "}}".

For example in the following string :

<p>{{ myFunction()&nbsp; }}</p>    
<p>&nbsp;</p>    
<p>{{ number|number_format(2, "&nbsp;.&nbsp;", '&nbsp;,&nbsp;')&nbsp;}}</p>    
<p>{% set myVariable = '&nbsp;&nbsp;' %}</p>

I want to replace every "&nbsp;" by "" except the "<p>&nbsp;</p>" one.

I'm doing the following :

$content = preg_replace('/({[{%].*)(&nbsp;)(.*[}%]})/', '$1 $3', $content);

but it replace only one occurrence of "&nbsp" in each brackets surroundings.

How to make it for all?

  • 写回答

3条回答 默认 最新

  • dream2891 2016-08-22 20:45
    关注

    I'm trying to replace all &nbsp; in twig syntax when it's surrounded by {% and %} or {{ and }}.

    If you are seeking for the easiest solution, just match all substrings that start with {{ and end with }}, or that start with {% and end with %} with '~{{.*?}}|{%.*?%}~s' regex, and use the pattern with the preg_replace_callback where you can further manipulate the match value inside the anonymous function:

    preg_replace_callback('~{{.*?}}|{%.*?%}~s', function ($m) {
         return str_replace('&nbsp;', '', $m[0]); 
    }, $s);
    

    See the PHP demo

    Pattern details:

    • {{.*?}} - match {{, then any 0+ characters as few as possible (due to the lazy *? quantifier) up to the closest }}
    • | - or
    • {%.*?%} - match {%, then any 0+ characters as few as possible up to the closest %}
    • ~s' - enables the DOTALL modifier so that.` could also match newline symbols.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据