I am new to regex, and as i have studied, the * matches zero or more and + matches one or more, so i started to test this:
<?php
preg_match("/a/", 'bbba',$m);
preg_match("/a*/", 'bbba',$o);
preg_match("/a+/", 'bbba',$p);
echo '<pre>';
var_dump($m);
var_dump($o);
var_dump($p);
echo '</pre>';
?>
but the result is that * didn't match any thing and returned empty while the letter a exists:
array(1) {
[0]=>
string(1) "a"
}
array(1) {
[0]=>
string(0) ""
}
array(1) {
[0]=>
string(1) "a"
}
so what i miss here.
/a/
matches the first a
in bbba
/a*/
matches 0 or more a
characters. There are 0 a
characters between the start of the string and the first b
so it matches there.
/a+/
matches 1 or more a
characters so it matches the first a
character
The thing to note here is that a regex will try and match as early in the string it is checking as possible.
a*
means match string which may NOT contain a
because *
matches zero or more,
hence pattern a*
will match even empty string.
To see all matches you can use preg_match_all
, like:
<?php
preg_match_all("/a*/", 'bbba', $o);
var_dump($o);
as result you will see:
array(1) {
[0]=>
array(5) {
[0]=>
string(0) ""
[1]=>
string(0) ""
[2]=>
string(0) ""
[3]=>
string(1) "a"
[4]=>
string(0) ""
}
}
hope it will help you.
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