dongnan1989 2017-01-12 20:30
浏览 30
已采纳

PHP preg_match_all与转义报价不匹配[关闭]

This code:

<?php
    $string = "\"single quote";
    preg_match_all("/\"/im", $string, $m);
    $all_quotes = count($m);
    preg_match_all("/\\\"/im", $string, $m);
    $escaped_quotes = count($m);

    echo "<pre>";
     echo "<b>string:</b> $string<br>";
     echo "<b>all quotes:</b> $all_quotes<br>";
     echo "<b>escaped quotes:</b> $escaped_quotes<br>";
    echo "</pre>";
?>

Is supposed to match all quotes, then match all escapes quotes, and echo the results. For some reason, for string "single quote it echoes both one quote and one escaped quote, however the pattern /\\\"/im matches nothing when executed in http://regexr.com with same string.

  • 写回答

1条回答 默认 最新

  • 普通网友 2017-01-12 20:34
    关注

    Edited:

    Ok, so first of all, you are getting count from preg_match_all as return value. The way you are doing it now will always show you 1 because preg_match_all returns array (with one element in your case).

    As Wiktor Stribiżew stated, you need to adjust your regex too

    preg_match_all("/\\\\\"/im", $string, $m);
    

    I'm not 100% sure that I understand your question but I'll try to answer it.

    You are probably expecting to see \" in your $string variable, right?

    But that's not the case. PHP will remove that backslash before saving your string. It's only hint for PHP that you want to get literal " and that you are not trying to end string here.

    In case you want (for any reason) get \" , you have to use code like this:

    $string = "\\\"single quote";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 SD的animatediff插件报错,只出单张图片,出不来动图
  • ¥28 opencv Cuda C++编译
  • ¥15 插入sim卡4g模组反复断连
  • ¥100 如何把 16bit Bayer 图像数据转换为 TIFF RGB
  • ¥15 进行基于用户的协同过滤推荐,使用准确率和召回率评价推荐模型的效果
  • ¥15 关于#cesium#的问题:cesium 根据经纬度、高度、方位角、俯仰角和距离求另一点高度
  • ¥15 word脚注设置不起空格符号
  • ¥15 为什么apriori的运行时间会比fp growth的运行时间短呢
  • ¥15 求解密json或者美化
  • ¥15 帮我解决一下膳食平衡的线性规划模型的数据实例