douzhaishan5462
2014-02-28 14:31
浏览 66
已采纳

计算字符串中不带反斜杠的引号数

I'm using the following expression to find the number of occurences of ' and " in a string I don't want the count to include \' or \".

$subStr = 'asdf"asdf""a\\"sdf\'asdf\'\'a\\\'sdf';
preg_match_all('/[^\\\\]\'|[^\\\\]\"/', $subStr, $matches);
echo count($matches[0]);

I expect it to return 6 but it only returns 4. I think this is because the strings "" and '' are only count once.

This is what $matches contain:

Array
(
    [0] => Array
        (
            [0] => f"
            [1] => f"
            [2] => f'
            [3] => f'
        )

)

Is there any way I can get the count of 6? Note that I also need to exclude the \" and \'.

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

我正在使用以下表达式查找'和<的出现次数 代码>“在一个字符串中我不希望计数包含 \' \”

   $ subStr ='asdf“asdf”“a \\”sdf \'asdf \'\'a \\\'sdf'; 
 npreg_match_all('/ [^ \\\\] \'| [^ \  \\\] \“/',$ subStr,$ matches); 
echo count($ matches [0]); 
   
 
 

我希望它返回6 但它只返回 4 。我认为这是因为字符串“”''只计算一次。

这是 $ matches 包含:

  Array 
(
 [0] =&gt; Array 
(\  n [0] =&gt; f“
 [1] =&gt; f”
 [2] =&gt; f'
 [3] =&gt; f'
)
 
)
 <  / code>  
 
 

有什么方法可以得到 6 的数量吗?注意我还需要排除 \“ \'

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dongzhuo6137 2014-02-28 14:33
    已采纳

    Why doesn't it work

    You can't use a character class to match a character not preceded by another character. This is because a character class (negated or not) must still match a character. For example, [^a]b does not mean "b not preceded by a". It means: "a character that's not a followed by b".

    The Solution

    If you want to match a single-quote or double-quote character not preceded by a backslash, then you'll have to use a lookaround expression (a negative lookbehind, specifically).

    The regex you're looking for is (?<!\\\\)[\'"].

    Autopsy:

    • (?<! - start of the lookbehind expression
      • \\\\ - match a literal backslash character
    • ) - end of the lookbehind expression
    • [\'"] - character class that matches a single character from the list "'

    Visual Representation:

    Visual Representation of the regex

    This effectively matches any single-quote / double-quote character that is not preceded by a literal backslash character.

    Using the above expression with preg_match_all is simple:

    $subStr = 'asdf"asdf""a\\"sdf\'asdf\'\'a\\\'sdf';
    preg_match_all('/(?<!\\\\)[\'"]/', $subStr, $matches);
    echo count($matches[0]); // => 6
    

    Demo

    评论
    解决 无用
    打赏 举报
查看更多回答(3条)

相关推荐 更多相似问题