2014-09-03 112 views
4

我試圖關閉這種字符串:關閉不全href標記

$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()因爲我希望它顯示爲有效的連結。

+0

什麼結果你現在開始? – Hendyanto 2014-09-03 06:45:19

+0

只處理''標記? – Raptor 2014-09-03 06:45:55

+0

可以提供什麼樣的輸入?像你提供的字符串? – user4035 2014-09-03 06:46:29

回答

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> 
+0

謝謝。它的工作 – kimbarcelona 2014-09-03 07:04:47

+1

@ kimbarcelona肯定沒有問題 – Ghost 2014-09-03 07:05:31

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>