preg replace — php: скобки / содержимое из массива?

Если у меня есть такая строка:

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

Я хочу чтобы

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

Как мне это сделать?

0

Решение

С некоторыми предположениями о фактическом синтаксисе вашей строки BBCode-ish следующее (шт) регулярное выражение может быть достаточно.

<?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

2

Другие решения

Других решений пока нет …