2014-09-03 107 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>