-2

I have been trying to create a plagiarism webpage.It will take the input from a text box and search in Google. if found it will display the results. Now the problem is , its searching the whole text at once but i need that to search 10 words at a time, and should search till the end in loops of 10 words.

Here is my code:

//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;
chris85
  • 23,846
  • 7
  • 34
  • 51

3 Answers3

1

Something like this should do it

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
    }
}

This splits your string on every single space then generates a URL with the string encoded.

Demo: http://sandbox.onlinephpfunctions.com/code/6118501275d95762ce9238b91261ff435da4e8cf

Functions:
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.urlencode.php

Update (per every 10 words):

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";
    }
}

Demo: http://sandbox.onlinephpfunctions.com/code/7a676951da1521a4c769a8ef092227f2aabcebe1

Additional function:
Modulus Operator : http://php.net/manual/en/language.operators.arithmetic.php

chris85
  • 23,846
  • 7
  • 34
  • 51
0

One way to split the string into chunks with a certain amount of words could be:

[EDIT] a shorter way would be:

$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";
}
Ben
  • 21
  • 5
0

Not sure but I think you have to use + instead of %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;
Makesh
  • 1,236
  • 1
  • 11
  • 25
  • `+` and `%20` both work. http://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20 – chris85 Jul 17 '15 at 11:03