3

我有这个字符串$s

本说(#yellow)嘿

目前我正在使用:

$parts = array_filter(preg_split('/\s+/', $s));

所以我有一个数组元素的输出:

[0] ben
[1] say
[2] (#yellow)
[3] hey

是否可以创建这样的数组结构:

[0] ben
[1] say
[2] (
[3] #yellow
[4] )
[5] hey
4

5 回答 5

3

您可以将其拆分为Lookahead and Lookbehind Zero-Width Assertions

$parts = array_filter(preg_split('/\s+|(?=[()])|(?<=[()])/', $s));
于 2012-09-13T11:32:29.170 回答
1

那么你可以试试这个替换:

$s = str_replace(array('(', ')'), array('( ', ' )'), $s);
$parts = array_filter(preg_split('/\s+/', $s));

这里的诀窍是在 your 和 word 之间添加一个空格,(以便将其拆分。但是,它仅适用于您的示例。诸如此类的事情((可能会导致一些不需要的结果。如果是这样,您可以尝试使用 preg_replace 代替。

于 2012-09-13T11:24:57.860 回答
0
<?php

// function to explode on multiple delimiters
function multi_explode($pattern, $string, $standardDelimiter = ':')
{
    // replace delimiters with standard delimiter, also removing redundant delimiters
    $string = preg_replace(array($pattern, "/{$standardDelimiter}+/s"), $standardDelimiter, $string);

    // return the results of explode
    return explode($standardDelimiter, $string);
}

// test

    // set up variables
    $string = "zero  one | two :three/ four\ five:: six|| seven eight nine\n ten \televen twelve thirteen fourteen fifteen";
    $pattern = '/[:\|\\\\\/\s]/';  // colon (:), pipe (escaped '\|'), slashes (escaped '\\\\' and '\/'), white space (\s)

    // call function
    $result = multi_explode($pattern, $string);

    // display results
    var_dump($result);

?>

来源: http: //php.net/manual/en/function.explode.php示例

于 2012-09-13T11:25:33.133 回答
0

一个可以完全按照需要工作的班轮(您甚至不需要array_filter):

$s = "ben say (ewfs) as";
$parts = preg_split('/\s+|(\()|(\))/', $s, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)

/*
Array(
  0 => "ben",
  1 => "say",
  2 => "(",
  3 => "ewfs",
  4 => ")",
  5 => "as",
)
*/
于 2012-09-13T11:30:46.280 回答
-2

这将起作用:

$parts = array_filter(preg_split('/[\s\(\)]+/', $s));
于 2012-09-13T11:25:19.483 回答