在字符串中查找多个 url. [英] Finding multiple urls in a string.

查看:38
本文介绍了在字符串中查找多个 url.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 $resource = "THIS IS ABOUT WWW.JONAKCOMPUTERS.COM, HTTP://HIGHLOW.COM, AND TESTINGSERVER1.COM"

并且我想将三个网址提取到另一个类似于以下内容的字符串中:

and I want to pull out the three urls into another string that is similar to:

 $all_urls = "JONAKCOMPUTERS.COM - HIGHLOW.COM - TESTSERVER1.COM

我从其他人那里发现的:

I found this by someone else:

$pattern = '#(www\.|https?:\/\/){1}[a-zA-Z0-9]{2,}\.[a-zA-Z0-9]{2,}(\S*)#i';
preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER);

但它不会只拉jonakcomputers.com"http://url"或www.url"

But it doesn't pull "jonakcomputers.com" only "http://url" or "www.url"

对不起,我只是想说明最后不区分大小写.我总能把它大写.我需要在页面加载之前执行此操作,因此它可能是 javascript 或 php.

Sorry for the caps, I just wanted to make it clear that its not case sensitive at the end. I can always capitalize it. I need to do this before the page loads, so it could be javascript or php.

如果我可以拔出一个,我想我可以做一个循环来不断检查新的,直到它用完.

If I could pull one out I think I could do a loop to keep checking for new ones till it runs out.

感谢任何愿意提供帮助的人.

Thanks for anyone willing to help out.

推荐答案

我在控制台中运行您的代码,只是调整了最后一个片段中的变量名称,以便:

I ran your code in a console, just adjusting the variable name in the last snippet so that:

php > $resource = "THIS IS ABOUT WWW.JONAKCOMPUTERS.COM, HTTP://HIGHLOW.COM, AND TESTINGSERVER1.COM"
php > $pattern = '#(www\.|https?:\/\/){1}[a-zA-Z0-9]{2,}\.[a-zA-Z0-9]{2,}(\S*)#i';
php > preg_match_all($pattern, $resource, $matches, PREG_PATTERN_ORDER);
php > var_dump($matches);
array(3) {
    [0]=>
        array(2) {
            [0]=>
                string(23) "WWW.JONAKCOMPUTERS.COM,"
            [1]=>
                string(19) "HTTP://HIGHLOW.COM,"
        }
    [1]=>
        array(2) {
            [0]=>
                string(4) "WWW."
            [1]=>
                string(7) "HTTP://"
        }
    [2]=>
        array(2) {
            [0]=>
                string(1) ","
            [1]=>
                string(1) ","
        }
}

您在 preg_match 返回中看到的是一个多维数组,其中包含以下内容:

What you see in the preg_match return is a multidimensional array w/ the following:

0:完整匹配

1:子模式 1 匹配

2:子模式 2 匹配

我看到的唯一解决方法是您需要稍微调整 RegExp 以解决缺少 ww 或 http 的问题.所以只需将其用于模式:

The only fix I see is that you'll need to adjust the RegExp slightly to account for the lack of ww or http. so just use this for pattern:

$pattern = '#(www\.|https?:\/\/)?[a-zA-Z0-9]{2,}\.[a-zA-Z0-9]{2,}(\S*)#i';

并且您的 $matches 现在应该包含所有 3 个.

and your $matches should now contain all 3.

这篇关于在字符串中查找多个 url.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆