2018-04-26 14:51
浏览 529


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)

    ['{',  '}',  '{',  '}',  '{',  '}' ],
    ['{ ', '} ', '{ ', '} ', '{ ', '} '],

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 { { {.

图片转代码服务由CSDN问答提供 功能建议


我的尝试是解决Vue.js对于从服务器端传递的数据的插值安全问题(Vue.js将尝试评估两个花括号之间的任何内容)。 目标是:

  1. 要始终确保两个花括号之间的空格
  2. 不要在不必要的地方添加额外的空格。


     ['{','}','  {','}','{','}'],
     ['{','}','{'  ,'}','{','}'],
     $ value 


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

    因此它会检查任何未跟随的匹配字符 空格并在两个字符之间插入空格。


    Ex : {{{返回 {{{,但预期输出为 {{{

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drox90250557
    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: The +++ markers were added to show that the third { doesn't match the regex and no replacement occurs for it.

    点赞 评论