How to return substrings in a string delimited by delimiters?

2

My problem is this: I have a string "Olá [eu] sou uma [string]" , how would I return the substrings that are within the delimiters "[" and "]" ?

* When I say return, I mean an array like that of the function explode.

    
asked by anonymous 06.11.2017 / 16:48

1 answer

1

You can use a regular expression to house the text inside brackets with the preg_match_all() function. Since what matters is inside a group you must access the returned array at the 1 index and then make a foreach to access all the captured texts. Ex echo $m[1][0]

$str= "Olá [eu] sou uma [string]";
$regex = '#\[([\w\s]+)\]#';

preg_match_all($regex, $str, $m);

echo "<pre>";
print_r($m);

Output:

Array
(
    [0] => Array
        (
            [0] => [eu]
            [1] => [string]
        )

    [1] => Array
        (
            [0] => eu
            [1] => string
        )

)
    
06.11.2017 / 17:19