2010-05-03 98 views
0

我想拿出那个创建了一个数组,看起来像下面的一个正则表达式,从以下字符串正则表达式的preg_match | preg_match_all在PHP

$str = 'Hello world [something here]{optional}{optional}{optional}{n possibilities of this}'; 

到目前为止,我有/^(\*{0,3})(.+)\[(.*)\]((?:{[a-z ]+})?)$/

Array 
(
    [0] => Array 
     (
      [0] => Hello world [something here]{optional}{optional}{optional}{n possibilities of this} 
      [1] => 
      [2] => Hello world 
      [3] => something here 
      [4] => {optional} 
      [5] => {optional} 
      [6] => {optional} 
      [7] => ... 
      [8] => ... 
      [9] => {n of this} 
     ) 
) 

这会是一个很好的方法吗?谢谢

+0

它是如何重要得到结果数组精确的问题?此外,是你想要匹配的“真实”字符串还是一个简单的例子? – salathe 2010-05-03 20:50:59

回答

0

我想你会需要两个步骤。

  1. (.+)\[(.+)\](.+)将让你Hello worldsomething here{optional}...{optional}

  2. \{(.+?)\}应用到上一步的最后一个元素将会得到可选的参数。

0

这是我认为的做法是更清洁比你要求为:

代码:(PHP Demo)(Pattern Demo

$str = 'Hello world [something here]{optional}{optional}{optional}{n possibilities of this}'; 
var_export(preg_split('/ *\[|\]|(?=\{)/',$str,NULL,PREG_SPLIT_NO_EMPTY)); 

输出:

array (
    0 => 'Hello world', 
    1 => 'something here', 
    2 => '{optional}', 
    3 => '{optional}', 
    4 => '{optional}', 
    5 => '{n possibilities of this}', 
) 

preg_split()将在三次可能的事件中破坏你的字符串(re在这个过程中移动这些事件):

  • *\[表示零个或多个空格,后面跟着一个方括号。
  • \]表示方括号。
  • ?=\{)表示一个零长度字符(就在......之前的位置)一个开放的大括号。

*我的模式在]{之间生成一个空元素。为了消除这个无用的元素,我添加了PREG_SPLIT_NO_EMPTY标志给函数调用。