-1

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.

user7401478
  • 1,372
  • 1
  • 8
  • 25
  • The `"\""` does not contain a backslash. Check [this demo to see how to declare a backslash in a PHP string literal](http://ideone.com/c2In3Z). – Wiktor Stribiżew Jan 12 '17 at 20:53
  • Possible duplicate of [Right way to escape backslash \[ \ \] in PHP regex?](http://stackoverflow.com/questions/11044136/right-way-to-escape-backslash-in-php-regex) – 4castle Jan 12 '17 at 21:15

1 Answers1

0

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";
Elon Than
  • 9,603
  • 4
  • 27
  • 37