php: brackets/contents 来自数组?

php: brackets/contents from a array?

如果我有这样的字符串:

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

我想要那个

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

我该怎么做?

根据对您的 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 / )
                (?# 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