php – 将字符串分解为令牌,保持引用的substr完整

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 将字符串分解为令牌,保持引用的substr完整脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我不知道我在哪里看到它,但任何人都可以告诉我如何使用 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+#',PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

脚本宝典总结

以上是脚本宝典为你收集整理的php – 将字符串分解为令牌,保持引用的substr完整全部内容,希望文章能够帮你解决php – 将字符串分解为令牌,保持引用的substr完整所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。