关闭不完整的href标签

时间:2014-09-03 06:44:13

标签: php html

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

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

3 个答案:

答案 0 :(得分: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 :(得分:0)

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

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

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

"></a>

答案 2 :(得分: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>