【问题标题】:php: get text of <a> tag having another tag inside itphp:获取 <a> 标签的文本,其中包含另一个标签
【发布时间】:2023-03-27 14:36:01
【问题描述】:
<a href="http://corporate.mattel.com/privacy-policy.aspx" class="privacy">
    <b>Primary Text</b> Secondary Text
</a>

我需要标签方式的文本,输出应该是“Primary Text Secondary Text”。

请帮助构建一个正则表达式来实现这个目的。

目前,我正在使用以下正则表达式:-

$regex = "/<a[\s]+[^>]*?href[\s]?=[\s\"\']+"."(.*?)[\"\']+.*?>"."([^<]+|.*?)?<\/a>/";

这个正则表达式给了我一个正确的输出:-

<a href="http://corporate.mattel.com/privacy-policy.aspx" class="privacy">
    Primary Text
</a>

【问题讨论】:

标签: php html regex


【解决方案1】:

您不应该使用正则表达式解析 html,而是使用 php DOM Parser
要删除b 标签,请使用strip_tags,即;

$html = file_get_contents("http://www.website.php");
/* 
OR 
$html = '<a href="http://corporate.mattel.com/privacy-policy.aspx" class="privacy">
    <b>Primary Text</b> Secondary Text
</a>';
*/
# Create a DOM parser object
$dom = new DomDocument();
@$dom->loadHTML($html);
$urls = $dom->getElementsByTagName('a');

foreach ($urls as $url) {
   $url->nodeValue = strip_tags($url->nodeValue);
} 
echo $dom->saveHTML();

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多