在PHP中从字符串中提取数字


Extract the number from a string in PHP

如何在PHP中从以下字符串中提取数字12345 ?

<span id="jordan934" itemprop="distance"><span class='WebDistance'>#$@20B9;&nbsp;</span>12345</span></h3>

我一直在使用下面的代码,直到'#$@20B9'字符串不在里面。

 $results = $dom->query('#jordan934"]');
        $distance = false;
        if (count($results)) {
$distance = (int)trim($results->current()->textContent);
}
        return $distance;
    }

尝试使用正则表达式

$str = 'jordan934';
preg_match_all('!'d+!', $str, $matches);
print_r($matches);

可以使用dom对象

<?php
$html = '<span id="jordan934" itemprop="distance"><span class=''WebDistance''>#$@20B9;&nbsp;</span>12345</span></h3>';
$dom = new DomDocument();
$dom->loadHTML($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(@class, '$classname')]");
var_dump($nodes);

另一个不为人知的功能是:

$str = 'jordan934';
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
http://php.net/manual/pl/function.filter-var.php