1

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?

2
  • 1
    Do you need to only get one DDAADD value? Or preg_split('~[][]~', $s) to get 3 values like $first, $second, and $third? Commented Mar 22, 2017 at 8:02
  • yes - I need the 3 strings.. thanks for your answer! Commented Mar 22, 2017 at 8:26

1 Answer 1

2

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].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.