Search code examples
phpregexpreg-match

php regular expression not returning matches


I have a really simple regular expression setup.

preg_match('/[0-9]*/', $item, $id);

$item's string value is "<li class="page_item page-item-29 current_page_item"><a href="http://dcdc.siretesting.com/programs/child-care/" title="Child Care">Child Care</a></li>"

when I print_r($id) I get an empty array Array ( [0] => )

I tested using http://regexpal.com/ and it selects like I would expect. It highlights the number 29

I can't figure out why in PHP it's not matching properly.


Solution

  • You're probably misguided by your pattern:

    /[0-9]*/
    

    The * signals that you want to match zero or more characters. preg_match does this, it finds zero of the character class [0-9] successfully and returns you the empty string.

    You might meant this:

    /[0-9]+/
    

    The + signals that you want to match one or more instead.

    Regexpal will give you all matches not only the first one. See with preg_match_all: Demo.