gpt4 book ai didi

php - 关闭不完整的 href 标签

转载 作者:可可西里 更新时间:2023-10-31 23:20:06 25 4
gpt4 key购买 nike

我正在尝试关闭这种字符串:

$link = 'Hello, welcome to <a href="www.stackoverflow.com';

echo $link;

如何修复不完整的 href 标签?我希望它是:

$link = 'Hello, welcome to <a href="www.stackoverflow.com"></a>'; // no value between <a> tag is alright.

我不想使用 strip_tags()htmlentities() 因为我希望它显示为工作链接。

最佳答案

不太擅长正则表达式,但您可以使用 DOMDocument 进行变通。示例:

$link = 'Hello, welcome to <a href="www.stackoverflow.com';

$output = '';
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($link);
libxml_clear_errors();
// the reason behind this is the HTML parser automatically appends `<p>` tags on lone text nodes, which is weird
foreach($dom->getElementsByTagName('p')->item(0)->childNodes as $child) {
$output .= $dom->saveHTML($child);
}

echo htmlentities($output);
// outputs:
// Hello, welcome to <a href="www.stackoverflow.com"></a>

关于php - 关闭不完整的 href 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25637874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com