在字符串中查找 URL


finding URLs within a string

我有一个包含URL的字符串,我希望能够选择整个字符串。我的意思是分解成一个数组,并替换为不同的 URL。我只是在努力弄清楚如何获取完整的URL,这可能是为了搜索http的strpos,然后是下一个空格,下一个空格的strpos,但我似乎无法弄清楚如何实现这一点。

$test = 'testing the test http://www.effef.com this is the end';
echo $pos = strpos($test,'http');

在这个字符串中,我们希望得到字符串'http://www.effef.com'

如何创建字符串的变量,该变量是字符串中的URL?

你不需要在数组中分解它并循环访问它来替换它。您可以将preg_replace用于您的目的。

$string = 'testing the test http://www.effef.com this is the end http://www.effef.com';
$replacement = 'http://www.newurl.com';
$regex = '/http:'/'/([^'s]+)/';
// if you are always sure that the url you want to replace is same then
// $regex = '/http':'/'/www'.effef'.com/';
$new_string = preg_replace($regex, $replacement, $string);
var_dump($new_string);

这是工作 php-fiddle

但是,如果您出于任何原因想在数组中获取它,您可以使用preg_match_all

preg_match_all($regex, $string, $matches);
var_dump($matches);

试试这个:

$test = 'testing the test http://www.effef.com this is the end http://www.facebook.com';
$arr = explode(" ", $test);
 foreach ($arr as $key => $value) {
     if (strpos($value, 'http') !== false) { echo $value."<br />"; }
 }
你可以

试试

$string = "testing the test https://www.effef.com this is the end";
if (preg_match('/https?:'/'/[^'s"<>]+/', $string, $find_url)) {
$url = $find_url[0];
echo $url;
}

对我来说,它回显了网址 http://www.effef.com/