Jelly Jelly - 1 month ago 11
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]);

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:



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



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


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) {

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