Reputation:
I was wondering how can I create preg_match
for catching:
id=4
4
being any number and how can I search for the above example in a string?
If this is could be correct /^id=[0-9]/
, the reason why I'm asking is because I'm not really good with preg_match
.
Upvotes: 0
Views: 667
Reputation: 13404
You should go with the the following:
/id=(\d+)/g
id=
- Literal id=
(\d+)
- Capturing group 0-9
a character range between 0
and 9
; +
- repeating infinite times /g
- modifier: global. All matches (don't return on first match)If you want to grab all ids and its values in PHP you could go with:
$string = "There are three ids: id=10 and id=12 and id=100";
preg_match_all("/id=(\d+)/", $string, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => id=10
[1] => id=12
[2] => id=100
)
[1] => Array
(
[0] => 10
[1] => 12
[2] => 100
)
)
Note: If you want to match all you must use /g
modifier. PHP doesn't support it but has other function for that which is preg_match_all
. All you need to do is remove the g
from the regex.
Upvotes: 1
Reputation: 194
for 4 being any number, we must set the range for it:
/^id\=[0-9]+/
\
escape the equal-sign, plus after the number means 1 or even more.
Upvotes: 2