PHP将术语分解为数组,将带引号的文本保留为单个数组项 [英] PHP explode terms in to array, retain quoted text as single array item

查看:30
本文介绍了PHP将术语分解为数组,将带引号的文本保留为单个数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从表单中得到以下字符串...

I have the following string from a form...

Opera添加跨平台硬件"踢屁股"-嬉皮士

Opera "adds cross-platform hardware" "kicks butt" -hippies

总的来说,我一直在使用以下内容...

In general I've simply been using the following...

$p0 = explode(' ',$string);

但是,现在我想将所有引号运算符作为一个数组项维护,而不是让它们创建像"addscross-platformhardware"这样的单个项.

However now I want to maintain any and all quote operators as a single array item instead of having them create individual items like "adds, cross-platform and hardware".

我想让该字符串最终创建一个像这样的数组...

I want to have that string end up creating an array like this...

Array
(
    [0] => 'Opera',
    [1] => 'adds cross-platform hardware',
    [2] => 'kicks butt',
    [3] => '-hippies'
)

我通常宁愿尽可能在大多数情况下不使用正则表达式.

I generally prefer to not use regex for most things whenever possible.

推荐答案

您可以使用preg_match_all(...):

$text = 'Opera "adds cross-platform hardware" "kicks butt" -hippies';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $text, $matches);
print_r($matches);

这篇关于PHP将术语分解为数组,将带引号的文本保留为单个数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆