View Full Version : prevent " "s from explode()ing
Xelopheris
Fri 8th Aug '03, 2:41am
Is there any way to not have stuff between quotes explode, or to recombine everything between quotes afterwards?
Faruk
Fri 8th Aug '03, 5:48am
What do you mean? In what circumstance does something between quotes 'automatically' explode? o_O
Icheb
Fri 8th Aug '03, 7:31am
He uses explode() on a string and doesn't want text between quotes to be processed by explode()...
Maybe strip the quoted text and add it after you used explode() ? Or you have to create your own function, explode() alone can't do it.
Faruk
Fri 8th Aug '03, 7:44am
Yeah but I wonder what he is exploding on, cos explode() itself doesn't do anything with " unless you specify it to, but then you're being silly :)
Icheb
Fri 8th Aug '03, 7:51am
Not with quotes, with the text between quotes.
Chen
Fri 8th Aug '03, 10:10am
$query = '"foo" one two "three four" five "six"';
// You should process $query a bit here, for example trimming and contracting multiple spaces into one
$queryBits = explode('"', $query);
$result = array();
if ($query{0} == '"') {
do {
$first = array_shift($queryBits);
} while (trim($first) == '');
$result[] = $first;
}
for ($i = 0; $i < count($queryBits); $i++) {
if (($queryBits[$i] = trim($queryBits[$i])) == '') {
continue;
}
if ($i % 2 == 0) {
$result = array_merge($result, explode(' ', $queryBits[$i]));
} else {
$result[] = $queryBits[$i];
}
}
print_r($result);Output:
Array
(
[0] => one
[1] => two
[2] => three four
[3] => five
[4] => six
)Please note I have taken quite a few shortcuts so if you want the code to be 100% reliable you will need to play with it a little. Also, there are countless other methods for doing the same thing and this may not be the fastest way. :) Someone with good PCRE knowledge migth be able to pull this quickly with preg_split().
(WYSIWYG editor ruined my tabs. :()
Chen
Fri 8th Aug '03, 10:29am
Here's another solution (prettier :)):
define('MD5MICRO', md5(microtime()));
function hide_spaces(&$string, $key, $modvalue) {
if ($key % 2 == (int) $modvalue) {
$string = str_replace(' ', MD5MICRO, $string);
}
}
function show_spaces(&$string, $key) {
$string = str_replace(MD5MICRO, ' ', trim($string));
}
$query = '"foo" one two "three four" five "six"';
$queryBits = explode('"', $query);
array_walk($queryBits, 'hide_spaces', $query{0} == '"');
$queryBits = explode(' ', implode(' ', $queryBits));
array_walk($queryBits, 'show_spaces');
$queryBits = array_filter($queryBits, 'strlen');
print_r($queryBits);
vBulletin® v3.8.0 Beta 4, Copyright ©2000-2008, Jelsoft Enterprises Ltd.