PHP/正则表达式:如何获取 HTML 标记的字符串值?

2022-08-30 12:50:28

我需要正则表达式或preg_match的帮助,因为我在这些方面还没有那么有经验,所以这是我的问题。

我需要获取值“get me”,但我认为我的函数有错误。html 标记的数量是动态的。它可以包含许多嵌套的html标签,如粗体标签。此外,“get me”值是动态的。

<?php
function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname>(.*?)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
$txt = getTextBetweenTags($str, "font");
echo $txt;
?>

答案 1
<?php
function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
$txt = getTextBetweenTags($str, "font");
echo $txt;
?>

这应该可以解决问题


答案 2

试试这个

$str = '<option value="123">abc</option>
        <option value="123">aabbcc</option>';

preg_match_all("#<option.*?>([^<]+)</option>#", $str, $foo);

print_r($foo[1]);

推荐