note 16621 added to function.explode
| From: | cleong at letstalk dot com | Date: | Tue, 06 Nov 2001 23:58:10 +0000 |
| Subject: | note 16621 added to function.explode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-20534@lists.php.net to get a copy of this message | ||
A version of explode() that parses quoted text into one element, with the option to bypass null
entry:
function ExplodeQuoted($glue, $open_quote_char, $close_quote_char, $str, $no_empty_entry = false)
{
$result = array();
$len = strlen($str);
$glue_len = strlen($glue);
$index = 0;
while($index <= $len)
{
if($str[$index] == $open_quote_char)
{
$end_index = $index;
while(($end_index = strpos($str, $close_quote_char, $end_index + 1)) != false
&& ($end_index + 1 != $len)
&& (substr($str, $end_index + 1, $glue_len) != $glue));
if($end_index)
{
$new_entry = substr($str, $index + 1, $end_index - $index - 1);
$index = $end_index + $glue_len + 1;
}
else
{
$new_entry = substr($str, $index + 1);
$index = $len + 1;
}
}
else
{
$end_index = strpos($str, $glue, $index);
// if($end_index || !is_string($end_index)) // for PHP versions that don't support !==
if($end_index !== false)
{
if(!$no_empty_entry || $end_index > $index)
{
$new_entry = substr($str, $index, $end_index - $index);
}
$index = $end_index + $glue_len;
}
else
{
$new_entry = substr($str, $index);
$index = $len + 1;
}
}
if(!$no_empty_entry || $new_entry)
{
$results[] = $new_entry;
}
}
return $results;
}
$words = ExplodeQuoted(' and ', '(', ')',
'Leo and Tolstoy and (War and Peace)');
Returns "Leo", "Tolstoy", and "War and Peace".
--
http://www.php.net/manual/en/function.explode.php
http://master.php.net/manage/user-notes.php?action=edit+16621
http://master.php.net/manage/user-notes.php?action=delete+16621
http://master.php.net/manage/user-notes.php?action=reject+16621