gpt4 book ai didi

PHP分解字符串,但将引号中的单词视为单个单词

转载 作者:IT王子 更新时间:2023-10-28 23:59:52 24 4
gpt4 key购买 nike

如何分解以下字符串:

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);

关于PHP分解字符串,但将引号中的单词视为单个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com