note 29775 modified in function.explode by aidan
| From: | aidan@php.net | Date: | Sun, 27 Jun 2004 14:27:46 +0000 |
| Subject: | note 29775 modified in function.explode by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-71927@lists.php.net to get a copy of this message | ||
Here's a little function similar to the above which will traverse a string, but pay attention
to quotes inline. I.e., I needed to parse something like this into an array:
one two "third thing" "fourth thing" five
It's pretty slow, but it works.
<?php
function opt_explode($echar, $str) {
if (strlen($echar) != 1 || strlen($str) == 0) {
return 0;
}
$str = trim($str);
// input string index counter
$idx=0;
// output array element counter
$arr=0;
while($idx < strlen($str)) {
if($str[$idx] == '"') {
// quoted field
$idx++;
while ($idx < strlen($str)) {
// look for ending quote
if($str[$idx] == '"') {
$idx++;
$arr++;
break;
}
$newstrarr[$arr] = $newstrarr[$arr] . $str[$idx];
$idx++;
}
} elseif ($str[$idx] == $echar) {
// normal delimiter, advance element
$arr++;
} else {
// must be normal char, tack onto current element
$newstrarr[$arr] = $newstrarr[$arr] . $str[$idx];
}
$idx++;
}
return $newstrarr;
}
?>
--was--
Here's a little function similar to the above which will traverse a string, but pay attention
to quotes inline. I.e., I needed to parse something like this into an array:
one two "third thing" "fourth thing" five
It's pretty slow, but it works.
function opt_explode($echar, $str) {
if (strlen($echar) != 1 || strlen($str) == 0) {
return 0;
}
$str = trim($str);
// input string index counter
$idx=0;
// output array element counter
$arr=0;
while($idx < strlen($str)) {
if($str[$idx] == '"') {
// quoted field
$idx++;
while ($idx < strlen($str)) {
// look for ending quote
if($str[$idx] == '"') {
$idx++;
$arr++;
break;
}
$newstrarr[$arr] = $newstrarr[$arr] . $str[$idx];
$idx++;
}
} elseif ($str[$idx] == $echar) {
// normal delimiter, advance element
$arr++;
} else {
// must be normal char, tack onto current element
$newstrarr[$arr] = $newstrarr[$arr] . $str[$idx];
}
$idx++;
}
return $newstrarr;
}
http://php.net/manual/en/function.explode.php