检查字符串是否已被超链接

时间:2011-05-05 01:41:55

标签: php html hyperlink

我应该使用什么正则表达式来检测我想要超链接的文本已经被超链接。

示例:

我用

$text = preg_replace('/((http)+(s)?:\/\/[^<>\s]+)/i', '<a href="\\0">\\0</a>', $text);

链接常规网址和

$text = preg_replace('/[@]+([A-Za-z_0-9]+)/', '@<a href="http://twitter.com/#!/\\1">\\1</a>', $text);

链接Twitter句柄。

我想检测我要去超链接的文本是否已经包含在<a href=""></a>中。

4 个答案:

答案 0 :(得分:1)

也许不是答案,而是另一种可能的解决方案;您还可以搜索以查看是否存在元素

$text = '<a href="#">here</a>';
if (gettype(strpos($text, "<a")) == "integer"){
  //<a start tag was found
};

或者只是剥离所有标签,无论如何都要建立链接

$text = '<a href="#">here</a>'; 
echo '<a href="my-own-url">' . strip_tags($text) . '</a>';

答案 1 :(得分:0)

简单,首先替换常规网址,因为它不会影响以@开头的任何内容,因为没有网址以@开头。然后更换推文句柄。

这样你就不需要检测它是否已被超链接。

答案 2 :(得分:0)

if (strpos($str, '<a ') !== FALSE) echo 'ok';

else echo 'error';

答案 3 :(得分:0)

$html = '<a href="#">Stephen Ou</a>';

$str = 'Stephen Ou';

if (strlen(str_replace($str, '', $html)) !== strlen($html)) {

    echo 'I got a feeling';

}