问题描述:

Just for fun, I'm trying to code something that will scan a website for YouTube URLs and save them. The URLs will not be within tags so I need to use regex. I have that part down. But how I do go about echoing the URLs from an array?

What I have so far:

<?php

$website = file_get_contents('http://boards.4chan.org/mu/res/41283979');

$reg_exURL = "/(?:https?://)?(?:www\.)?youtu(?:be\.com/watch\?(?:.*?&(?:amp;)?)?v=|\.be/)([\w‌​\-]+)(?:&(?:amp;)?[\w\?=]*)?/";

if(preg_match($reg_exURL, $website, $urls)) {

// Echo all values in the array

foreach ($urls as $url) {

echo $url;

}

} else {

echo "No URLs Found.";

}

?>

But when I echo $url, I just get the word "Array". I want to see all the URLs, preferably one on each line.

网友答案:

Notice how 4chan adds <wbr> tags in the youtube IDs, probably as a security against things like this. You have to remove those tags from the source first with a replace.

Then you can use regex to match all links in the source, keeping in mind that a youtube video ID consists of letters, numbers, _, - and is always 11 characters long.

$website = str_replace("<wbr>","",file_get_contents('http://boards.4chan.org/mu/res/41283979'));

$regex = "/(https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=[A-Za-z0-9_-]{11}/";
preg_match_all($regex , $website, $urls, PREG_SET_ORDER); 

foreach ($urls as $url)
    echo $url[0] . "<br>";
网友答案:

print_r is used to output arrays:

http://php.net/manual/en/function.print-r.php

网友答案:

You can just use print_r($url) or var_dump($url). These are standard ways to print arrays.

网友答案:

You can do this using a foreach loop.

<?php

$website = file_get_contents('http://boards.4chan.org/mu/res/41283979');
$reg_exURL = "/(?:https?:\/\/)?(?:www\.)?youtu(?:be\.com\/watch\?(?:.*?&(?:amp;)?)?v=|\.be\/)([\w‌​\-]+)(?:&(?:amp;)?[\w\?=]*)?/";
if(preg_match($reg_exURL, $website, $urls)) {
    // Echo all values in the array
    foreach ($urls as $url) {
        echo $url;
    }
} else {
    echo "No URLs Found.";
}

?>
相关阅读:
Top