tags:

views:

21

answers:

2

Hello, i want to split the searchrequest into parts, if there's nothing to find. example: "nelly furtado ft. jimmy jones" -> no results -> try to find with nelly, furtado, jimmy or jones.. i have an api url.. thats the difficult part.. i show you some of the actually snippets:

$query = urlencode (strip_tags ($_GET[search]));

and

 $found = '0';
    if ($source == 'all')
    {
      if (!($res = @get_url ('http://api.example.com/?key=' . $API . '&phrase=' . $query . ' . '&sort=' . $sort)))
      {
        exit ('<error>Cannot get requested information.</error>');
        ;
      }

how can i put a else request in this snippet, like if nothing found take the first word, or the second word, is this possible? or maybe you can tell me were i can read stuff about this function?

thank you!!

A: 

It sounds like you want to split your search terms based on whitespace. explode() can handle this pretty easily if you just want to use spaces (you could use preg_split() for more complicated splitting).

  $url = 'http://api.example.com/?key='.$API.'&amp;sort='.$sort.'&amp;phrase='; 
  if (!($res = @get_url ($url.$query)))
  {
    //couldn't find it, try piece by piece
    $pieces = explode(' ',$query);
    foreach($pieces as $p) {
       if (! empty($p)) {
         $res = @get_url ($url.$p);
         if ($res) {
            //success, do something
         }
       }
    }

    if (! $res) {
       //no results
    }
  }
zombat
A: 

Well, you've used urlencode() on $query, so after that all the words will be separated by a + character. You can then split the words out like this:

$words = explode('+', $query);

After that, just do a for loop over each of the words and send queries again (I don't know what your $source = 'all' line is for, so I'll just leave it there).

for ($i = 0; $i < count($words); $i++)
{
    if ($source == 'all')
    {
        if (!($res = @get_url ('http://api.example.com/?key=' . $API . '&phrase=' . $words[$i] . ' . '&sort=' . $sort)))
        {
            exit ('<error>Cannot get requested information.</error>');
        }
    }
}
Chad Birch