[英]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.