note 38414 deleted from function.explode by nlopess
| From: | nlopess@php.net | Date: | Fri, 19 Dec 2003 17:58:33 +0000 |
| Subject: | note 38414 deleted from function.explode by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-62253@lists.php.net to get a copy of this message | ||
Note Submitter: Architect (mail@tomcully.com)
----
Here's a function some may find handy:
Say you are using explode to generate an array of search terms when writing a search engine, and
want to split the terms on a space (or spaces) e.g.
search: 'beer vodka pubs'
explode(" ",$terms) gives '[0] => beer, [1] =>vodka, [2] => pubs'
If you want a quoted string to return as a single entry, here's a simple function that allows
for quoted strings (without using a regexp), e.g.
search: 'beer "Katy Dalys" pubs'
explode(" ",$terms) gives '[0] => beer, [1] =>"Katy, [2] =>
Dalys", [3] => pubs'
websearch_exlpode(" ",$terms) gives '[0] => beer, [1] => Kety Dalys, [2] =>
pubs'
Hope it helps ;-)
<?php
function websearch_explode($terms) {
$qmode=false;
$out=array();
$cstr="";
$lastchar=" ";
for ($pos=0; $pos<=strlen($terms); $pos++) {
$char=substr($terms,$pos,1);
switch($qmode) {
case false: {
// No Quotes
if (($char==" ") and ($lastchar!=" ")) {
array_push($out,$cstr); $cstr="";
} elseif ($char=='"') {
$qmode=true;
} else {
$cstr.=$char;
}
$lastchar=$char;
break;
}
case true: {
// Quotes
if ($char=='"') {
$qmode=false;
$lastchar=" ";
} else {
$cstr.=$char;
}
break;
}
}
}
if ($cstr!="") { array_push($out,$cstr); }
return($out);
}
?>