user2580401
user2580401

Reputation: 1889

php - split string by spaces and quotes without spaces into array

Lets say I've a following strings

$string1 = 'hello world my name is'

and

$string2 = '"hello world" my name is'

using this with string1:

preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $string1, $matches);

I get an array:

echo $matches[0][0]//hello
echo $matches[0][1] //world

using the same but with string2:

preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $string2, $matches);

I get an array:

echo $matches[0][0] //"hello world"
echo $matches[0][1] //my

but if my string is:

 " hello world " my name is 
//^^          ^^(notice the spaces at beginning and end ), 

I would get:

echo $matches[0][0] //" hello world "

when I really want to get

"hello world"

how to modify the first argument in preg_match_all? any other simple solution? thanks

Upvotes: 1

Views: 190

Answers (1)

Kausha Mehta
Kausha Mehta

Reputation: 2928

Try below code:

$string = '" hello world " my name is';
$string = preg_replace('/"\s*(.*?)\s*"/', '"$1"', $string);
echo ($string);
echo "<br />";
// OUTPUt : "hello world" my name is

preg_match_all('/"(?:\\.|[^\\"])*"|\S+/', $string, $matches);
print_r($matches);
// OUTPUt : Array ( [0] => Array ( [0] => "hello world" [1] => my [2] => name [3] => is ) )

echo implode(' ', $matches[0]);
// OUTPUt : "hello world" my name is

Upvotes: 2

Related Questions