PHP爆炸功能 [英] PHP explode function

查看:107
本文介绍了PHP爆炸功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让用户输入标签:

windows linux mac os x

windows linux "mac os x"

然后将它们按空格分开,但也将 mac os x识别为一个整体。

and then split them up by white space but also recognizing "mac os x" as a whole word.

是否可以将explode函数与其他函数结合使用?

Is this possible to combine the explode function with other functions for this?

必须有一种方法。

推荐答案

只要引号内不能有引号(例如, foo bar 是不允许的),则可以使用正则表达式执行此操作,否则需要一个完整解析器。

As long as there can't be quotes within quotes (eg. "foo\"bar" isn't allowed), you can do this with a regular expression. Otherwise you need a full parser.

应该这样做:

function split_words($input) {
  $matches = array();
  if (preg_match_all('/("([^"]+)")|(\w+)/', $input, $reg)) {
    for ($ii=0,$cc=count($reg[0]); $ii < $cc; ++$ii) {
      $matches[] = $reg[2][$ii] ? $reg[2][$ii] : $reg[3][$ii];
    }
  }
  return $matches;
}

用法:

$input = 'windows linux "mac os x"';
var_dump(split_words($input));

这篇关于PHP爆炸功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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