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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵