Regex to find a string in square brackets []

I want to grab the text in square brackets in the html line below. But the regular expression, which I have below, does not receive the "image" and "imagealt" images separately, but returns the "image" instead of "alt =" [imagealt]. If I pull alt = "[imagealt]" from the string, it will return as I expected / want.

$html = '<h2>[title]</h2>
<div class="content"><img src="[image]" alt="[imagealt]" /></div>
<div class="content">[text]</div>';

preg_match_all("^\[(.*)\]^",$html,$fields, PREG_PATTERN_ORDER);

echo "<pre>";
print_r($fields);
echo "</pre>";


Array
(
    [0] => Array
        (
            [0] => [title]
            [1] => [image]" alt="[imagealt]
            [2] => [text]
        )

    [1] => Array
        (
            [0] => title
            [1] => image]" alt="[imagealt
            [2] => text
        )

)
+5
source share
3 answers

your regular expression is greedy. you need to stop him, to be greedy, to do what you want. Learn a little about greed here .

, , , , .

?, php, :

preg_match_all("^\[(.*?)\]^",$html,$fields, PREG_PATTERN_ORDER);
+7
preg_match_all("#\[[^\]]*\]#",$html,$fields, PREG_PATTERN_ORDER);

^ , # | , . , [^\]*] .*?, , ], . , , m, , .

+5

use

     preg_match_all("^\[(.*?)\]^",$html,$fields, PREG_PATTERN_ORDER);

Optional ?means "unwanted match", it will stop after detection]

+3
source

All Articles