从网页中获取 <b> 标记之间的值


Get values in between <b> tags from web page

我正在尝试从外部网页中提取两条数据。页面上有两个标签,我需要的数据都在这两个标签中。

如何从两个标签中获取数据?

我尝试了几种不同的东西,但似乎都没有奏效。这是我上次尝试的:

$dom = new DOMDocument;
$dom->loadHtmlFile('url');
$xpath = new DOMXPath($dom);
$elements = $xpath->query('b');
if ($elements->length) {
    echo "found: ", $elements->item(0)->getAttribute('value');
} else {
    echo "not found";
}

正则表达式并不总是答案,事实上,对于我的整个 Web 平台来说,我的 PHP 中只有不到十几个正则表达式实例。

$p = explode($elements,'<b>')[1];
$p = explode($p,'</b>)[0];

使用:

<?php
    $str = "This is a test string <b>I want this sub string</b> this is a test string.";
    preg_match("~".preg_quote("<b>")."(.*?)".preg_quote("</b>")."~", $str, $output);
    echo $output[1];
?>

输出:

I want this sub string

试试这个:

function get_str_btwn($string, $start, $end)
{
    $string = " " . $string;
    $ini    = strpos($string, $start);
    if ($ini == 0)
        return "";
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}
$dom=file_get_contents('url');
echo get_str_btwn($dom,"<b>","</b>");