问题
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
.
回答1:
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.
回答2:
You should go with the the following:
/id=(\d+)/g
Explanations:
id=
- Literalid=
(\d+)
- Capturing group0-9
a character range between0
and9
;+
- repeating infinite times/g
- modifier: global. All matches (don't return on first match)
Example online
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);
Output:
Array
(
[0] => Array
(
[0] => id=10
[1] => id=12
[2] => id=100
)
[1] => Array
(
[0] => 10
[1] => 12
[2] => 100
)
)
Example online
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.
来源:https://stackoverflow.com/questions/19700380/catching-ids-and-its-values-from-a-string-with-preg-match