Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 744
Styphon Avatar asked Oct 28 '14 10:10

Styphon


People also ask

What does preg_ match return?

The preg_match() function returns whether a match was found in a string.

How does preg_ match work?

PHP | preg_match() Function. This function searches string for pattern, returns true if pattern exists, otherwise returns false. Usually search starts from beginning of subject string. The optional parameter offset is used to specify the position from where to start the search.


2 Answers

It returns 2 elements because:

Element 0 captures the whole matched string

Elements 1..N capture dedicated matches.

PS: another way of expressing the same could be

(?<=")[^"]+(?=")

which would capture exactly the same but in that case you don't need additional capturing group.

Demo: http://regex101.com/r/lF3kP7/1

like image 157
zerkms Avatar answered Sep 19 '22 17:09

zerkms


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.

like image 43
Thilo Habenreich Avatar answered Sep 22 '22 17:09

Thilo Habenreich