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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据