Catching ids and its values from a string with preg_match

左心房为你撑大大i 提交于 2019-12-11 20:15:14

问题


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= - 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)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!