如何从给定的 HTML 标记中提取特定的子字符串,而不确定其长度


How do I extract a specific substring from a given HTML tag, without knowing for certain its length?

我想做这样的事情:

<?php
$text = "<font style='color: #fff'>";
$replaceandshow = str_replace("<font style='"?'">", "the font style is ?", $text);
echo $replaceandshow;
?>

比如 ? 是颜色:#fff,但我希望 PHP 会自己跟踪它,可能吗 + 如果可能,我该怎么做?

PS:有人给了我一个代码,但它现在正在工作,它为我显示了一个白页。

<?php
$colorstring = "<font style='#fff'>";
$searchcolor = preg_replace('[a-fA-F0-9]{3,6}','[font style=$1]Test[/font]',$colorstring);
echo $searchcolor;

感谢您的帮助。

您看到白页,因为错误报告已关闭。代码中的错误是 preg_replace 中缺少分隔符。此外,要使用反向引用,您应该将匹配所需的表达式括在括号中。

preg_replace('/([a-fA-F0-9]{3,6})/','the font style is $1',$colorstring);

应给出正确的输出。

您可以考虑使用更严格的表达式,因为当前表达式非常开放地匹配其他字符串,如"FFFont"。需要注意的另一件事是,该表达式可能会导致输出类似。

<font style='color: the color is #fff'>

尝试:

/<font style='color: #([a-fA-F0-9]{3,6})'>/

由于您基本上需要从任何 HTML 中提取任何属性,因此您可以使用 php XML 解析来执行此操作。

<?php
$doc=new DOMDocument();
$doc->loadHTML("<html><body>Test<br><font style='color: #fff;'>hellow</font><a href='www.somesite.com' title='some title'>some site</a></body></html>");
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$fonts=$xml->xpath('//font');
foreach ($fonts as $font) {
    echo 'font style = '.$font['style']."<br />";
}
$as=$xml->xpath('//a');
foreach ($as as $a) {
    echo 'href = '.$a['href'] . ' title = ' . $a['title']."<br />";
}
?>

这将返回:

font style = color: #fff;
href = www.somesite.com title = some title

您可以对需要提取的每个 HTML 标记使用不同的 foreach 循环,然后输出所需的任何属性。

答案基于如何使用 php 从 html 中提取 img src、title 和 alt?

这将适用于简单的style属性:

$text = "<font style='color: #fff'>";
preg_match("/<font style=[''"]([^''"]+)[''"]>/", $text, $matches);
echo "The font style is ".$matches[1];

对于更复杂的内容(例如:如果它包含引号),您需要使用 HTML 解析器,例如 http://www.php.net/manual/en/class.domdocument.php