我试图在php中创建一个用于显示消息的脚本。如果消息包含网址,那么我希望将此地址显示为链接。这是我成功运作的代码:
<?php
if( (substr( $message, 0, 8 ) === "https://") || (substr( $message, 0, 7 ) === "http://") ){
echo "<a href='$message' target='_blank'> $message </a>";
}else{
echo " $message ";
}
?>
如果用户仅在消息中插入网址,则工作正常:“http://google.com”如果用户在网址之前或之后插入文字,则问题就会出现。例如,如果写入:“访问http://google.com网站”,那么它会将所有短语作为链接,并且不会识别带有网址的字词。知道如何解决这个问题吗?
答案 0 :(得分:1)
我在课堂上使用它:
public static function CreateLinks($text) {
return preg_replace('@(https?://([-\w.]+[-\w])+(:\d+)?(/([\w-.~:/?#\[\]\@!$&\'()*+,;=%]*)?)?)@', '<a href="$1" target="_blank">$1</a>', $text);
}
要在没有课程的情况下使用它,请执行以下操作:
$message = preg_replace('@(https?://([-\w.]+[-\w])+(:\d+)?(/([\w-.~:/?#\[\]\@!$&\'()*+,;=%]*)?)?)@', '<a href="$1" target="_blank">$1</a>', $message);
所以在一个测试案例中:
$message = "Hello, take a look at http://www.google.com or wait! Maybe you where looking for http://www.bing.com";
$message = preg_replace('@(https?://([-\w.]+[-\w])+(:\d+)?(/([\w-.~:/?#\[\]\@!$&\'()*+,;=%]*)?)?)@', '<a href="$1" target="_blank">$1</a>', $message);
echo $message;
将输出:
Hello, take a look at <a href="http://www.google.com" target="_blank">http://www.google.com</a> or wait! Maybe you where looking for <a href="http://www.bing.com" target="_blank">http://www.bing.com</a>
因此,最后您的代码只能由一行代替!替换这个:
if( (substr( $message, 0, 8 ) === "https://") || (substr( $message, 0, 7 ) === "http://") ){
echo "<a href='$message' target='_blank'> $message </a>";
}else{
echo " $message ";
}
由此:
$message = preg_replace('@(https?://([-\w.]+[-\w])+(:\d+)?(/([\w-.~:/?#\[\]\@!$&\'()*+,;=%]*)?)?)@', '<a href="$1" target="_blank">$1</a>', $message);
答案 1 :(得分:1)
您可以将filter_var与FILTER_VALIDATE_URL
:
$words = explode(" ", $message);
$_words = array();
foreach($words as $word){
if(filter_var($word, FILTER_VALIDATE_URL) === false){
$_words[] = $word;
}
else{
$_words[] = "<a href=\"$word\">$word</a>";
}
}
echo implode(" ", $_words);
答案 2 :(得分:0)
Jan Goyvaerts,Regex Guru,在他的博客中描述得非常好
http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/
要查找多行字符串中的所有匹配项,请使用
preg_match_all('/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/i', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];
你可以使用preg_match函数来获得单一匹配