0

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.

Greg
  • 481
  • 1
  • 5
  • 21

2 Answers2

2

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.

Levin
  • 194
  • 5
  • You don't have to escape `\\` really – Ilia Ross Oct 31 '13 at 07:26
  • 1
    @user2865738 Actually, it will not grab a number but result will be numerical string if you cast it to int it will be limited either to `(2^32) / 2 - 1` or `(2^64) / 2 - 1` number, depending you use 32 bit or 64 bit system, respectively. – Leri Oct 31 '13 at 07:28
  • 1
    @Ilia Rostovtsev you are right, i confused just now. and `\d` can instead `[0-9]`. – Levin Oct 31 '13 at 07:35
1

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.

Ilia Ross
  • 13,086
  • 11
  • 53
  • 88