从字符串获取URL

编程入门 行业动态 更新时间:2024-10-21 03:45:06
本文介绍了从字符串获取URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

For a little while now I've been searching for a code to get URL's out of a string using PHP. I'm basically trying to get a Shortened URL out of a message, and then later do a HEAD request to find the actual link.

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

Anyone have any code that returns URLs from strings?

谢谢.

编辑Ghost Dog:

以下是我正在解析的示例:

Here is a sample of what I am parsing:

$test = "I am testing this application for test YAY!";

这是我得到的解决问题的答案:

And here is the response I got that solved it:

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

有关详细信息,请参见答案.

See Answer for the Details.

推荐答案

以下代码可能会有所帮助(请参阅MadTechie的最新文章):

This code may be helpful (see MadTechie's latest post):

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

<?php $string = "some random text tinyurl/9uxdwc some google random text tinyurl/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']; } ?>

更多推荐

从字符串获取URL

本文发布于:2023-11-08 13:52:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569554.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!