PHP 分解字符串,但将引号中的单词视为单个单词
如何将以下字符串分解
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);
但我的代码将每个单词划分为一个数组。如何将引号内的单词视为一个单词?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
preg_match_all(...)
:它将产生:
正如您所看到的,它还解释了带引号的字符串中的转义引号。
编辑
简短说明:
如果匹配
%22
而不是双引号,您将执行以下操作: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:使用
str_getcsv()
会容易得多。给你
This would have been much easier with
str_getcsv()
.Gives you
您也可以尝试这个多重爆炸功能
You can also try this multiple explode function
我来到这里遇到了与此类似的复杂字符串分割问题,但是这里的答案都没有完全符合我的要求 - 所以我写了自己的答案。
我将其发布在这里只是为了对其他人有帮助。
这可能是一种非常缓慢且低效的方法 - 但它对我有用。
用法如下。
explode_adv
有 5 个参数:[
、(
等。]
、)
等。"
、'
、等。方法可能有缺陷 - 欢迎编辑。
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.
在某些情况下,鲜为人知的
token_get_all()
< /a> 可能有用:结果:
In some situations the little known
token_get_all()
might prove useful:Results: