Parsing string into array if user types in quotation marks

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rpaulpen
Forum Newbie
Posts: 2
Joined: Fri Dec 19, 2008 1:30 pm

Parsing string into array if user types in quotation marks

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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")
rpaulpen
Forum Newbie
Posts: 2
Joined: Fri Dec 19, 2008 1:30 pm

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

Post by rpaulpen »

thanks! That did the trick.

Much appreciated.

R
Post Reply