开发者

php string search - grabbing specific urls

I have this string that may contain some urls that I need to grab. For instance, if the user does:

www.youtube ...

or

开发者_运维知识库www.vimeo ...

or

http://www.youtube ...

or

HttP://WwW.viMeo

I need to grab it (until he finds a space perhaps). and store it on a already created array.

The need is to separate the vimeo links from the youtube ones and place each of those on the appropriate video object.

I'm not sure if this is possible, I mean, if the URL coming from the browser could be used to be placed on a predefined video object. If it is, then this is the way to go (so I believe).

If all this is feasible, can I have your help in order to build such a rule?

Thanks in advance


This matches the links you need, and store them in a 2D array by site name:

$video_links = array();
if (preg_match_all("'(http://)?(www[.])?(youtube|vimeo)[^\s]+'is",$str,$n)) {
    foreach ($n[3] as $key => $site)
    {
        $video_links[$site][] = $n[0][$key];
    }
}

What does this do?

This match separates 3 + 1 parts of the needed urls in $str, which is your string:

  • Part 0: the whole match (your video link)
  • Part 1: http:// (optional)
  • Part 2: www. (optional)
  • Part 3: vimeo or youtube

preg_match_all returns a 2D array with the above part numbers at first level, and every match inside is the part of each match. So you iterate part 3 of the match ($n[3]), and use the array keys to reference part 0 ($n[0][$key]), and arrange them in a nice 2D array like this:

$video_links = array (
    'vimeo' => array (
        0 => 'vimeo link 1',
        1 => 'vimeo link 2',
        // ...
    ),
    'youtube' => array (
        0 => 'youtube link 1',
        1 => 'youtube link 2',
        // ...
    )
);


What you should do is first replace all instance of http:// and www. with nothing, and then prepend it back on to the string, this makes the string consistent

str_replace(array("http://www.","http://"),"",$url);
$url = "http://" . $url;

then you can use parse_url to check the data like so

$Data = parse_url($url);

Then just check your values accordingly.

switch(strtolower($Data['host']))
{
    case "youtube.com":
        // :)
    break;
    case "vimeo.com":
        // :)
    break;
    case "something.tld":
        // :)
    break;
}

The dump of $Data would output something like so:

[scheme] => http
[host] => youtube.com
[user] => 
[pass] => 
[path] => /watch
[query] => v=r8FVAHuQvjc&feature=topvideos
[fragment] =>

you can now just go

$lastSegment = $Data["path"] . "?" . $Data["query"];

which would return something like /watch?v=r8FVAHuQvjc&feature=topvideos

if you wanted individual items from the query such as the video id you can then go:

parse_str($Data["query"],$result);
echo $result["v"];

which would just output the video id.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜