Как может я взрывать следующую строку:
Lorem ipsum "dolor sit amet" consectetur "adipiscing elit" dolor
в
array("Lorem", "ipsum", "dolor sit amet", "consectetur", "adipiscing elit", "dolor")
Так, чтобы текст в цитате рассматривали как отдельное слово.
Вот то, что я имею на данный момент:
$mytext = "Lorem ipsum %22dolor sit amet%22 consectetur %22adipiscing elit%22 dolor"
$noquotes = str_replace("%22", "", $mytext");
$newarray = explode(" ", $noquotes);
но мой код делит каждое слово на массив. То, как я делаю слова в кавычках, рассматривало как одно слово?
Вы можете использовать preg_match_all (. ..)
:
$text = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing \\"elit" dolor';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $text, $matches);
print_r($matches);
, что даст:
Array
(
[0] => Array
(
[0] => Lorem
[1] => ipsum
[2] => "dolor sit amet"
[3] => consectetur
[4] => "adipiscing \"elit"
[5] => dolor
)
)
И, как вы можете видеть, он также учитывает экранированные кавычки внутри строк в кавычках.
РЕДАКТИРОВАТЬ
Краткое объяснение:
" # match the character '"'
(?: # start non-capture group 1
\\ # match the character '\'
. # match any character except line breaks
| # OR
[^\\"] # match any character except '\' and '"'
)* # end non-capture group 1 and repeat it zero or more times
" # match the character '"'
| # OR
\S+ # match a non-whitespace character: [^\s] and repeat it one or more times
И в случае соответствия % 22
вместо двойных кавычек вы должны сделать:
preg_match_all('/%22(?:\\\\.|(?!%22).)*%22|\S+/', $text, $matches);