关闭不完整的href标签

4

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

$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(),因为我希望它显示为一个可工作的链接。


你现在得到了什么结果? - Hendyanto
仅处理 <a> 标签? - Raptor
$link = '你好,欢迎来到<a href="www.stackoverflow.com">标签</a>'; - jayadevkv
href标签来自MySQL数据,它破坏了后续的显示。 - kimbarcelona
是的,目前正在处理 href。我认为正则表达式可以处理这个问题? - kimbarcelona
显示剩余2条评论
3个回答

3

虽然不是很擅长使用正则表达式,但您可以使用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>

1
@kimbarcelona 确定,没问题。 - Kevin

0

只需在从mysql中提取数据时修改数据即可。 在获取mysql数据的代码中添加类似以下内容:

...
$link = < YOUR MYSQL VALUE > . '"></a>';
...

或者你可以在数据库上运行一个查询来更新值,追加字符串:
"></a>

0

您提到可能对正则表达式解决方案感兴趣,这是我能想到的:

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

// Pattern matches <a href=" where there the string ends before a closing quote appears.
$pattern = '/(<a href="[^"]+$)/';

// Perform the regex search
$isMatch = (bool)preg_match($pattern, $link);

// If there's a match, close the <a> tag
if ($isMatch) {
    $link .= '"></a>';
}

// Output the result
echo $link;

输出:

Hello, welcome to <a href="www.stackoverflow.com"></a>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接