2

我想根据以下规则打破一个字符串:

  1. 所有连续的字母数字字符,加上点 ( .) 必须被视为一部分
  2. 所有其他连续字符必须被视为一部分
  3. 1和的连续组合2必须被视为不同的部分
  4. 不得返回空格

例如这个字符串:

Method(hierarchy.of.properties) = ?

应该返回这个数组:

Array
(
    [0] => Method
    [1] => (
    [2] => hierarchy.of.properties
    [3] => )
    [4] => =
    [5] => ?
)

我没有成功preg_split(),因为 AFAIK 它不能将模式视为要返回的元素。

有什么简单的方法可以做到这一点吗?

4

2 回答 2

3

您可能应该使用preg_match_all而不是 preg_split。

preg_match_all('/[\w|\.]+|[^\w\s]+/', $string, $matches);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => Method
            [1] => (
            [2] => hierarchy.of.properties
            [3] => )
            [4] => =
            [5] => ?
        )

)
于 2011-06-27T12:18:11.150 回答
0

这应该做你想要的:

$matches = array();
$string = "Method(hierarchy.of.properties) = ?";
foreach(preg_split('/(12|[^a-zA-Z0-9.])/', $string, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $match) {
    if (trim($match) != '')
        $matches[] = $match;
}

我使用循环删除所有空格匹配,因为据我所知 preg_split() 中没有适合您的功能。

于 2011-06-27T12:18:37.943 回答