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 \'.

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)