phpregexpreg-match-allduplicate-data

Why is preg_match_all returning two matches?


I am trying to identify if a string has any words between double quotes using preg_match_all, however it's duplicating results and the first result has two sets of double quotes either side, where as the string being searched only has the one set.

Here is my code:

$str = 'Test start. "Test match this". Test end.';
$groups = array();
preg_match_all('/"([^"]+)"/', $str, $groups);
var_dump($groups);

And the var dump produces:

array(2) {
    [0]=>
    array(1) {
        [0]=>
        string(17) ""Test match this""
    }
    [1]=>
    array(1) {
        [0]=>
        string(15) "Test match this"
    }
}

As you can see the first array is wrong, why is preg_match_all returning this?


Solution

  • Hi if your are using print_r instead of vardump you will see the differences in a better way.

    Array
    (
        [0] => Array
            (
                [0] => "Test match this"
            )
    
        [1] => Array
            (
                [0] => Test match this
            )
    
    )
    

    The first contains whole string and the second is your match.