-2

我一直在尝试创建一个抄袭网页。它将从文本框中获取输入并在 Google 中搜索。如果找到它将显示结果。现在的问题是,它一次搜索整个文本,但我需要一次搜索 10 个单词,并且应该在 10 个单词的循环中搜索到最后。

这是我的代码:

//Google search code
if(isset($_POST['nm'])) {
     $query = $_POST["nm"];
     $string = str_replace(' ', '%20', $_POST["nm"]);
}
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=".$string;
4

3 回答 3

1

像这样的事情应该这样做

if(isset($_POST['nm'])) {
    $words = explode(' ', $_POST["nm"]);
    foreach($words as $word) {
        $url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=". urlencode($word);
        //make request
    }
}

这会在每个空格上拆分您的字符串,然后生成一个带有字符串编码的 URL。

演示:http ://sandbox.onlinephpfunctions.com/code/6118501275d95762ce9238b91261ff435da4e8cf

功能: http:
//php.net/manual/en/function.explode.php
http://php.net/manual/en/function.urlencode.php

更新(每 10 个字):

if(isset($_POST['nm'])) {
    $words = explode(' ', $_POST["nm"]);
    foreach($words as $wordcount => $word) {
        if($wordcount % 10 == 0 && !empty($wordcount)) {
             echo 'Hit 10th word, what to do?' . "\n\n";
        }
        $url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=". urlencode($word);
        echo $url . "\n";
    }
}

演示:http ://sandbox.onlinephpfunctions.com/code/7a676951da1521a4c769a8ef092227f2aabcebe1

附加功能:
模运算符: http: //php.net/manual/en/language.operators.arithmetic.php

于 2015-07-17T10:50:43.500 回答
0

将字符串拆分为具有一定数量单词的块的一种方法可能是:

[编辑] 更短的方法是:

$text = "This is some text to demonstrate the splitting of text into chunks with a defined number of words.";
$wordlimit = 10;
$words = preg_split("/\s+/",$text);  

$strings = array_chunk($words,$wordlimit);
foreach($strings AS $string){
    $url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=". urlencode(implode(" ", $string));
    echo $url."\n";
}
于 2015-07-17T11:01:43.767 回答
0

不确定,但我认为你必须使用+而不是%20

if(isset($_POST['nm'])) {
     $query = implode(' ', array_slice(explode(' ', $_POST['nm']), 0, 10));
     $string = urlencode ($query );
}
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=".$string;
于 2015-07-17T11:02:22.023 回答