Search code examples
phpregexstringtext-extraction

Extracting number from a string that looks like a function call with 1 parameter


I would like to extract a number from a string. The string looks something like this:

"visaObs(31124228);"

Here is my shot at it. It doesn't seem to get any matches:

preg_match('/visaObs((\d+));/s', $attribute, $match);
echo $match[0]; //undefined offset

Any ideas?


Solution

  • You must escape ( and ):

    preg_match('/visaObs[(](\d+)[)];/s', $attribute, $match);
    

    Example:

    $ cat /tmp/1.php
    <?
    $attribute = "visaObs(31124228);";
    preg_match('/visaObs[(](\d+)[)];/s', $attribute, $match);
    print $match[1];
    ?>
    $ php /tmp/1.php
    31124228
    

    If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.