如果我有这样的字符串:
$str = '[tr]Kapadokya[/tr][en]Cappadocia[/en][de]Test[/de]';
我想要那个
$array = array(
'tr' => 'Kapadokya',
'en' => 'Cappadocia',
'de' => 'Test');
我该怎么做?
答案 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',
),
)