如何运作preg_match_all()?
我想从字符串中获取一个数字:
例如:我有结果:
(62)
我只想要数字。并希望这样做几个字符串。 这就是我的尝试:
foreach($html2->find('small[class=menu-item__label__count]') as $aholder) {
$holderdes=$aholder->outertext;
preg_match_all('/([0-9]+)/', $holderdes,$num);
echo $num.'<br>';
返回的是#34;数组阵列数组...&#34;
答案 0 :(得分:0)
您应该打印$num[0];
foreach($num[0] as $pattern)
// do something with $pattern
你的正则表达式看起来也错了。如果你想匹配你需要做的(61)
(包括括号):
'/\(([0-9]+)\)/'
答案 1 :(得分:0)
如果你有像"(62)"
然后你可以使用它:
<?php
$str = '(62)';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
?>
输出:
Array
(
[0] => Array
(
[0] => 62
)
)
另外,如果你试图回应一个数组($num
),你就得不到errors
打开错误报告进行调试!
error_reporting(E_ALL);
ini_set("display_errors", 1);
答案 2 :(得分:0)
preg_match返回一个数组,可以从documentation看到。
如果要查看数组的所有内容,请使用
var_dump( $sum );
如果您只需要匹配,则必须解决该特定部分。
查看正则表达式快速参考
答案 3 :(得分:0)
此功能在php.net上完全explained
看看这个从字符串数组中提取数字的非常简单的例子:
<?php
$strings = array ("fHzZGh4JMyfpc5visCC3q1a1ICBLWXnmfxoRa70S9HXHjBSVI4",
"1LRWmzTQBErP6kIqXRLMgzWoVdOJKrLpUbL99sZ3XdtscAvydG",
"5OMbG1hFMrTkMeThw64E80QqfLvxbZjo3tlsVzeJiDCDAn4D6C",
"lrYFqKKtarRHfteYHUDx4KAEjssvs12Ix5u3YGQKATQBxtqAhn",
"W3a3n0jzXtM2l5i8tOVnxPbBeGAz0ChzDQ6qhReQkdHTQ4sLmz");
$nums = array ();
foreach ($strings as $string) {
preg_match_all('/\d+/', $string, $matches);
$nums[] = $matches;
}
print_r($nums);
这是输出:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 4
[1] => 5
[2] => 3
[3] => 1
[4] => 1
[5] => 70
[6] => 9
[7] => 4
)
)
[1] => Array
(
[0] => Array
(
[0] => 1
[1] => 6
[2] => 99
[3] => 3
)
)
[2] => Array
(
[0] => Array
(
[0] => 5
[1] => 1
[2] => 64
[3] => 80
[4] => 3
[5] => 4
[6] => 6
)
)
[3] => Array
(
[0] => Array
(
[0] => 4
[1] => 12
[2] => 5
[3] => 3
)
)
[4] => Array
(
[0] => Array
(
[0] => 3
[1] => 3
[2] => 0
[3] => 2
[4] => 5
[5] => 8
[6] => 0
[7] => 6
[8] => 4
)
)
)