从字符串获取一个URL(Get a URL from a String)

2019-06-26 06:00发布

一会儿我一直在寻找一个代码来获得URL的出了使用PHP的字符串。 基本上,我试图让一个缩短的URL出来的消息,再后来做一个HEAD请求,找到实际的链接。

任何人有从字符串返回网址的代码?

提前致谢。

编辑鬼狗:

下面是我解析的示例:

$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']; 
} 

请参阅详细的回答。

Answer 1:

此代码可能是有帮助的(见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']; } ?> 


Answer 2:

就像是:

$matches = array();
preg_match_all('/http:\/\/[a-zA-Z0-9.-]+\/[a-zA-Z0-9.-]+/', $text, $matches);
print_r($matches);

你需要调整正则表达式来得到你想要的东西。

要获得URL时,考虑简单的东西如:

curl -I http://url.com/path | grep Location: | awk '{print $2}'



文章来源: Get a URL from a String
标签: php string url