Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get string between two characters [string] ? PHP [duplicate]

Tags:

string

php

$string1 = "This is test [example]";
$string2 = "This is test [example][2]";
$string3 = "This [is] test [example][3]";

How can I get the following result?

For $string1 -> example
For $string2 -> example*2
For $string3 -> is*example*3
like image 696
dido Avatar asked Dec 16 '22 23:12

dido


1 Answers

preg_match_all('/\[([^\]]+)\]/', $str, $matches);

php > preg_match_all('/\[([^\]]+)\]/', 'This [is] test [example][3]', $matches);
php > print_r($matches);
Array
(
    [0] => Array
        (
            [0] => [is]
            [1] => [example]
            [2] => [3]
        )

    [1] => Array
        (
            [0] => is
            [1] => example
            [2] => 3
        )

)

And here's the explanation for the rregex:

\[ # literal [
( # group start
    [^\]]+ # one or more non-] characters
) # group end
\] # literal ]
like image 165
ThiefMaster Avatar answered Apr 27 '23 15:04

ThiefMaster