note 38414 added to function.explode
| From: | (mail@tomcully.com) | Date: | Fri, 19 Dec 2003 17:03:48 +0000 |
| Subject: | note 38414 added to function.explode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-62248@lists.php.net to get a copy of this message | ||
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);
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.explode.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+38414
Delete -- http://master.php.net/manage/user-notes.php?action=delete+38414&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+38414&report=yes
Search -- http://master.php.net/manage/user-notes.php