如何使用javascript从文本框中选择有限数量的单词?

时间:2015-07-17 10:32:30

标签: javascript php jquery json plagiarism-detection

我一直在尝试创建一个抄袭网页。它会从文本框中获取输入并在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;

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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";
}

答案 2 :(得分: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;