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?
The preg_match() function returns whether a match was found in a string.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With