How can I explode the following string:
Lorem ipsum "dolor sit amet" consectetur "adipiscing elit" dolor
into
array("Lorem", "ipsum", "dolor sit amet", "consectetur", "adipiscing elit", "dolor")
So that the text in quotation is treated as a single word.
Here's what I have for now:
$mytext = "Lorem ipsum %22dolor sit amet%22 consectetur %22adipiscing elit%22 dolor"
$noquotes = str_replace("%22", "", $mytext");
$newarray = explode(" ", $noquotes);
but my code divides each word into an array. How do I make words inside quotation marks treated as one word?
This would have been much easier with
str_getcsv()
.Gives you
In some situations the little known
token_get_all()
might prove useful:Results:
You could use a
preg_match_all(...)
:which will produce:
And as you can see, it also accounts for escaped quotes inside quoted strings.
EDIT
A short explanation:
And in case of matching
%22
instead of double quotes, you'd do:You can also try this multiple explode function
I came here with a complex string splitting problem similar to this, but none of the answers here did exactly what I wanted - so I wrote my own.
I am posting it here just in case it is helpful to someone else.
This is probably a very slow and inefficient way to do it - but it works for me.
Usage is as follows.
explode_adv
takes 5 arguments:[
,(
, etc.]
,)
, etc."
,'
, etc.This method probably has flaws - edits are welcome.