Если я понял, что вы спрашиваете, вы можете достичь этого, используя file_get_contents();
После использования file_get_contents($url)
, который дает вам строку, вы можете перебирать строку результата в поисках пробелов, чтобы разделить слова на части. Подсчитайте количество слов и сохраните слова в массиве соответственно. Затем просто выберите случайный элемент из массива, используя array_rand()
Однако иногда возникают проблемы с безопасностью file_get_contents()
.
Вы можете изменить это, используя следующую функцию:
function get_url_contents($url)
{
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
http://php.net/manual/en/function.curl-setopt.php <--- Объяснение о скручиваемости </p>
Пример кода:
$url = "http://www.xxxxx.xxx"; //Set the website you want to get content from
$str = file_get_contents($url); //Get the contents of the website
$built_str = ""; //This string will hold the valid URLs
$strarr = explode(" ", $str); //Explode string into array(every space a new element)
for ($i = 0; $i < count($strarr); $i++) //Start looping through the array
{
$current = @parse_url($strarr[$i]) //Attempt to parse the current element of the array
if ($current) //If parse_url() returned true(URL is valid)
{
$built_str .= $current . " "; //Add the valid URL to the new string with " "
}
else
{
//URL invalid. Do something here
}
}
$built_arr = explode(" ", $built_str) //Same as we did with $str_arr. This is why we added a space to $built_str every time the URL was valid. So we could use it now to split the string into an array
echo $built_arr[array_rand($built_arr)]; // Display a random element from our built array
Существует также более расширенная версия для проверки URL, с которой вы можете ознакомиться здесь:
http://forums.digitalpoint.com/showthread.php?t=326016
Удачи.