goldlife
goldlife

Reputation: 1989

PHP get string with preg match

I am sadly not so familar with regex - so someone can help me with this? I have this string:

$theString = 'MYSTRING-[DDAADD]-IS_SO_BEAUTYFULL'

And all what I want is to extract the content between the 2 square brackets, in this example I should get 'DDAADD'.

The target is to explode my string that I get 3 strings:

$first = 'MYSTRING-';
$second = 'DDAADD';
$third = '-IS_SO_BEAUTYFULL';

How do I reach it?

I try it with preg_match but I can't get it to work:

preg_match('/[^a-zA-Z0-9\[\]]+/', $string, $matches);

I also try this:

preg_match_all('/[A-Z\[\]]+/', $string, $matches);

Then I got my three strings, but without the '-'..

I try it whith preg_split but I don't reach my target properly:

preg_split("/\[([^\]]+)\]/", $myString);

Then I got only my 2 strings correct, but without the central part with DDAADD...

Can someone help me with this?

Upvotes: 1

Views: 827

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

Use preg_split with [][]+ regex to match one or more [ or ] symbols:

$s = "MYSTRING-[DDAADD]-IS_SO_BEAUTYFULL";
$arr = preg_split('~[][]+~', $s);
print_r($arr);

Output of the sample demo:

Array
(
    [0] => MYSTRING-
    [1] => DDAADD
    [2] => -IS_SO_BEAUTYFULL
)

Another approach is to use a preg_match with \[([^][]+)] regex (or \[([A-Z]+)]):

$s = "MYSTRING-[DDAADD]-IS_SO_BEAUTYFULL";
if (preg_match('~\[([A-Z]+)]~', $s, $res)) {
    echo($res[1] . "\n");
} // => DDAADD
if (preg_match('~\[([^][]+)]~', $s, $res)) {
    print_r($res[1]);
} // => DDAADD

See another demo

Here, \[ matches a [, ([A-Z]+) captures into Group 1 one or more uppercase letters (or [^][]+ matches 1 or more chars other than [ and ]) and ] matches a literal ]. The value is inside $res[1].

Upvotes: 2

Related Questions