我想找到文本中的所有链接,如下所示:
Test text http://hello.world Test text
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text
test text http://test.test/test
Run Code Online (Sandbox Code Playgroud)
我知道我需要使用preg_match_all,但只有头脑中的想法:从http | https | ftp开始搜索并在文本的空格或末尾出现的结束搜索,这就是我真正需要的所有内容,因此所有链接都可以正确找到.
任何人都可以帮助我使用php regexp模式?
我想我需要在模式结束时使用断言,但现在无法理解它们的正确用法.
有任何想法吗?感谢名单!
Jon*_*y 5 10
我会选择一些简单的东西 ~[a-z]+://\S+~i
所以它看起来像这样:
$pattern = '~[a-z]+://\S+~';
$str = 'Test text http://hello.world Test text
http://google.com/file.jpg Test text https://hell.o.wor.ld/test?qwe=qwe Test text
test text http://test.test/test';
if($num_found = preg_match_all($pattern, $str, $out))
{
echo "FOUND ".$num_found." LINKS:\n";
print_r($out[0]);
}
Run Code Online (Sandbox Code Playgroud)
产出:
FOUND 4 LINKS:
Array
(
[0] => http://hello.world
[1] => http://google.com/file.jpg
[2] => https://hell.o.wor.ld/test?qwe=qwe
[3] => http://test.test/test
)
Run Code Online (Sandbox Code Playgroud)
小智 5
function turnUrlIntoHyperlink($string){
//The Regular Expression filter
$reg_exUrl = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
// Check if there is a url in the text
if(preg_match_all($reg_exUrl, $string, $url)) {
// Loop through all matches
foreach($url[0] as $newLinks){
if(strstr( $newLinks, ":" ) === false){
$link = 'http://'.$newLinks;
}else{
$link = $newLinks;
}
// Create Search and Replace strings
$search = $newLinks;
$replace = '<a href="'.$link.'" title="'.$newLinks.'" target="_blank">'.$link.'</a>';
$string = str_replace($search, $replace, $string);
}
}
//Return result
return $string;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9863 次 |
| 最近记录: |