php:数组中的括号/内容?

时间:2015-02-19 10:27:59

标签: php preg-replace brackets

如果我有这样的字符串:

$str = '[tr]Kapadokya[/tr][en]Cappadocia[/en][de]Test[/de]';

我想要那个

$array = array(
'tr' => 'Kapadokya',
'en' => 'Cappadocia',
'de' => 'Test');

我该怎么做?

1 个答案:

答案 0 :(得分:2)

对于BBCode-ish字符串的实际语法有一些假设,以下(pc) regular expression可能就足够了。

<?php
$str = '[tr]Kapadokya[/tr][en]Cappadocia[/en][de]Test[/de]';

$pattern = '!
    \[
        ([^\]]+)
    \]
    (.+)
    \[
      /
        \\1
    \]
!x';

/* alternative, probably better expression (see comments)
$pattern = '!
    \[            (?# pattern start with a literal [ )
        ([^\]]+)  (?# is followed by one or more characters other than ] - those characters are grouped as subcapture #1, see below )
    \]            (?# is followed by one literal ] )
    (             (?# capture all following characters )
      [^[]+       (?# as long as not a literal ] is encountered - there must be at least one such character )
    )
    \[            (?# pattern ends with a literal [ and )
      /           (?# literal / )
      \1          (?# the same characters as between the opening [...] - that's subcapture #1  )
    \]            (?# and finally a literal ] )
!x';     // the x modifier allows us to make the pattern easier to read because literal white spaces are ignored
*/

preg_match_all($pattern, $str, $matches);
var_export($matches);

打印

array (
  0 => 
  array (
    0 => '[tr]Kapadokya[/tr]',
    1 => '[en]Cappadocia[/en]',
    2 => '[de]Test[/de]',
  ),
  1 => 
  array (
    0 => 'tr',
    1 => 'en',
    2 => 'de',
  ),
  2 => 
  array (
    0 => 'Kapadokya',
    1 => 'Cappadocia',
    2 => 'Test',
  ),
)

另见:http://docs.php.net/pcre