Hamza Kaya
Hamza Kaya

Reputation: 3

php: brackets/contents from a array?

If I have a string like this:

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

I want that

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

How do I do this?

Upvotes: 0

Views: 44

Answers (1)

VolkerK
VolkerK

Reputation: 96159

With a few assumptions about the actual syntax of your BBCode-ish string the following (pc) regular expression might suffice.

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

prints

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',
  ),
)

see also: http://docs.php.net/pcre

Upvotes: 2

Related Questions