Jelly Jelly - 2 days ago 6
PHP Question

PHP why doesn't preg_match work?

Hello I have the following code:

$headerOcc = substr_count($text, "[Image][");

if($headerOcc < '1'){
$text = $text;
}


for ($i=0; $i < $headerOcc; $i++) {
preg_match('/[Image\]\[(.*)\]/', $text, $match);
$headerTitle = ($match[1]);
print($headerTitle);
}


I also have the following variable:

$text = "Hello world [Image][61][Image][62]Hello world";


I want to find out if there is a part of the text that says [image][ID]. Obviously the ID will be replaced by a number and I want to get it. How can I get $headerTitle to return that ID inside the curly brackets. It currently gives me this when I print it:

61]**


**[Image][62

Which is not what I want. I want it to return:

61

62


What am i doing wrong and how can I fix it?

Answer

Use preg_match_all() and use \d+ to get the digits:

preg_match_all('/\[Image\]\[(\d+)\]/', $text, $matches);

Alternately you could match on NOT ], so ([^\]]+).

Then just loop $matches[1] to echo etc...

foreach($matches[1] as $headerTitle) {
    print($headerTitle);
}

No need for the substr_count() or any of the other stuff.

Comments