gpt4 book ai didi

php - 将字符串分解为标记,保持引用的 substr 完好无损

转载 作者:可可西里 更新时间:2023-11-01 13:18:28 27 4
gpt4 key购买 nike

我不知道我在哪里看到它,但谁能告诉我如何使用 php 和正则表达式完成此操作?

'this is a string "that has quoted text" inside.'

我希望能够像这样把它炸掉

[0]this
[1]is
[2]a
[3]string
[4]"that has quoted text"
[5]inside

保持引号不变。

最佳答案

你能试试下面的代码吗:

$str = 'this is a string  "that has quoted text" inside.';
var_dump ( preg_split('#\s*("[^"]*")\s*|\s+#', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) );

Output:
array(6) {
[0]=>
string(4) "this"
[1]=>
string(2) "is"
[2]=>
string(1) "a"
[3]=>
string(6) "string"
[4]=>
string(22) ""that has quoted text""
[5]=>
string(7) "inside."
}

这是 above working code on dialpad 的链接

更新:要转义支持,请尝试:

preg_split('#\s*((?<!\\\\)"[^"]*")\s*|\s+#', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

关于php - 将字符串分解为标记,保持引用的 substr 完好无损,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5475312/

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