gpt4 book ai didi

php - 从字符串中获取 URL

转载 作者:可可西里 更新时间:2023-11-01 13:42:22 25 4
gpt4 key购买 nike

一段时间以来,我一直在寻找使用 PHP 从字符串中获取 URL 的代码。我基本上是在尝试从消息中获取缩短的 URL,然后执行 HEAD 请求以查找实际链接。

有人有从字符串返回 URL 的代码吗?

提前致谢。

为幽灵狗编辑:

这是我正在解析的示例:

$test = "I am testing this application for http://test.com YAY!";

这是我得到的解决问题的回复:

$regex = '$\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]$i';

preg_match_all($regex, $string, $result, PREG_PATTERN_ORDER);
$A = $result[0];

foreach($A as $B)
{
$URL = GetRealURL($B);
echo "$URL<BR>";
}


function GetRealURL( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_USERAGENT => "spider",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
);

$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
return $header['url'];
}

有关详细信息,请参阅答案。

最佳答案

此代码可能会有帮助(请参阅 MadTechie 的最新帖子):

http://www.phpfreaks.com/forums/index.php/topic,245248.msg1146218.html#msg1146218

<?php
$string = "some random text http://tinyurl.com/9uxdwc some http://google.com random text http://tinyurl.com/787988";

$regex = '$\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]$i';

preg_match_all($regex, $string, $result, PREG_PATTERN_ORDER);
$A = $result[0];

foreach($A as $B)
{
$URL = GetRealURL($B);
echo "$URL<BR>";
}


function GetRealURL( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_USERAGENT => "spider",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
);

$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
return $header['url'];
}

?>

关于php - 从字符串中获取 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1146198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com