php:括号/数组中的内容?
如果我有这样一个字符串:php:括号/数组中的内容?,php,preg-replace,brackets,Php,Preg Replace,Brackets,如果我有这样一个字符串: $str = '[tr]Kapadokya[/tr][en]Cappadocia[/en][de]Test[/de]'; 我想要 $array = array( 'tr' => 'Kapadokya', 'en' => 'Cappadocia', 'de' => 'Test'); 如何做到这一点?对BBCode-ish字符串的实际语法进行一些假设,以下内容可能就足够了 <?php $str = '[tr]Kapadokya[/tr][en]C
$str = '[tr]Kapadokya[/tr][en]Cappadocia[/en][de]Test[/de]';
我想要
$array = array(
'tr' => 'Kapadokya',
'en' => 'Cappadocia',
'de' => 'Test');
如何做到这一点?对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);
另请参见:请记住,SO社区通常希望在提出问题之前多付出一些努力:您是如何解决问题的?你做了一些基础研究吗。。。。没有必要对回溯引用进行双重转义,您应该将
+
更改为[^[]+
或至少+?
以限制回溯(如果有多个翻译在同一行)。a)是的,可能;我从来不会这样做,因为我是在原处长大的C-developer(回到那些日子,叹气:D)一个错误。但你是对的。b)不,我不想;这是我在“一些假设”中的自由;-)但是是的,使用[^[]+
可以很容易地被认为是更好的。我们确实很少有关于这个bbcode的确切语法的信息,但它似乎是同一术语的连续翻译,所以我认为,轮到我了,这些标记不能包含嵌套的标记,但未来是通向所有可能的门。你的观点是完全有效的,因此不适用于公司他仔细考虑了答案。
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',
),
)