How to return substrings in a delimited string?

Asked

Viewed 26 times

2

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

*When I say return, I mean an array like the one of the function explodes.

1 answer

1


You can use a regular expression to house the text inside the brackets with the function preg_match_all(). Since what matters is inside a group you must access the array returned in the Indice 1 and then can do a foreach to access all 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);

Exit:

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

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

)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.