繁体   English   中英

关闭不完整的href标签

[英]Close incomplete href tag

我正试图关闭这种字符串:

$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>

只需在从mysql中提取数据时修改数据。 添加到从mysql获取数据的代码:

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

或者,您可以在数据库上运行查询以更新值,并附加字符串:

"></a>

您表示您可能对Regex解决方案感兴趣,所以这就是我能够提出的:

$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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM