Page 1 of 1

Parsing string into array if user types in quotation marks

Posted: Fri Dec 19, 2008 1:42 pm
by rpaulpen
Hi all,

I'm basically have a page where the user can type in something like

cars for sale in "St. Louis"

I've been using str_word_count to break the string into an array for each word. But, the problem I have is that I want the array to to return

cars
for
sale
in
st. louis

NOT

cars
for
sale
in
st.
louis

I'm wondering if there is a php function that will convert the string into an array but combine any words with quotation marks as one.

Thanks,

R

Re: Parsing string into array if user types in quotation marks

Posted: Fri Dec 19, 2008 2:15 pm
by requinix
First split the string on "s, and then only every other part of that array on spaces.

Code: Select all

$str = 'cars for sale in "St. Louis"';
$words = array();
 
$array = explode('"', $str);
// array = array("cars for sale in ", "St. Louis", "")
$i = 0; foreach ($array as $a) {
    if (!($a = trim($a))) continue;
    if ($i == 0) $words += explode(" ", $a); else $words[] = $a;
    $i = 1 - $i;
}
// words = array("cars", "for", "sale", "in", "St. Louis")

Re: Parsing string into array if user types in quotation marks

Posted: Fri Dec 19, 2008 3:32 pm
by rpaulpen
thanks! That did the trick.

Much appreciated.

R