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";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致