You are here: Breaking up search terms into an array intelligently « PHP « IT news, forums, messages
Breaking up search terms into an array intelligently

Posted by "Paul Groves" on 09/07/05 17:54

I want to be able to break up a number of search terms typed into an input
box into array, simple enough one would think, just use explode, e.g


$array = explode(" ", $string);


But what if I want to be able to cope with search terms seperated by > 1
space (a common typing error)? This should work:


function enhanced_explode($string) {
$array = preg_split ("/\s+/", $string);
return ($array);
}


But what if I want to allow "Google"-type search parameters, so that
something like the following is split into 3 search terms?:
firstsearchterm "second search term" thirdsearchterm
The following code will do the trick, but is slow and doesn't allow for
multiple spaces as the delimiter, nor the possibility of multiple delimiters
(e.g. " ", "+", "," etc.)


function explode2($delimeter, $string)
{
for ($i = 0; $i < strlen($string); $i++)
{
if ($string{$i} == '"')
{
if ($insidequotes)
$insidequotes = false;
else
$insidequotes = true;
}
elseif ($string{$i} == $delimeter)
{
if ($insidequotes)
{
$currentelement .= $string{$i};
}
else
{
$returnarray[$elementcount++] = $currentelement;
$currentelement = '';
}
}
else
{
$currentelement .= $string{$i};
}
}

$returnarray[$elementcount++] = $currentelement;

return $returnarray;
}

None of these solutions are ideal, I guess a clever regular exression
(preg_split) could solve this, but I'm not quite sure how - does anyone have
any ideas? Thanks

Paul

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация