douduikai0562 2018-04-26 14:51
浏览 1126
已采纳

始终使用正则表达式在两个字符之间添加空格

For those regex experts out there, can you help me tweak this regex to always add a whitespace between two matching characters.

My attempt is to resolve the interpolation security issue with Vue.js for data passed from the server side (Vue.js will try to evaluate anything between two curly braces). The goal is:

  1. To always ensure whitespace between two curly braces
  2. Not add additional whitespace where unnecessary.

My str_replace solution (which accomplishes goal #1 only)

str_replace(
    ['{',  '}',  '{',  '}',  '{',  '}' ],
    ['{ ', '} ', '{ ', '} ', '{ ', '} '],
    $value
);

My attempted regex thus far:

preg_replace('/({|}|{|}|{|})(\S)/', '$1 $2', $value);

So it checks for any matching character that isn't followed by whitespace and inserts whitespace between the two characters.

The regex works in most cases, but fails when you have three or more matching characters.

Ex: {{{ returns { {{ but the expected output would be { { {.

  • 写回答

1条回答 默认 最新

  • drox90250557 2018-04-26 15:01
    关注

    It doesn't work as you expect it because the first two { characters match the regex, the replacement is made then the search continues with the 3rd character of the input string

    You can solve this by turning the second parenthesis into a forward assertion. This way, the second } is not consumed on the first match and the next search starts with the second character of the input string:

    preg_replace('/({|}|{|}|{|})(?=\S)/', '$1 ', $value);
    

    There is only one capture group this way, $2 is always empty and it is not needed any more in the replacement string.

    See it in action: https://3v4l.org/CaMHS. The +++ markers were added to show that the third { doesn't match the regex and no replacement occurs for it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!