从字符串中提取数字

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?

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.

In regular expressions, a parenthesis is a special character. You should escape the parenthesis around the numbers

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

You must escape literal parenthesis:

/visaObs\((\d+)\);/

The s modifier is not needed, and your result is in $match[1] since it is the first capturing group.

You can find only the number by matching any amount of digits, and include what should surround it:

preg_match('/(?<=visaObs\()\d+(?=\))/', $attribute, $match);
var_dump($match);