Skip to content
Advertisement

Get multiple values from preg_match_all and use of foreach

I have tried to find a solution for my specific problem. I have a regex where I find two specific values. These values need to be combined in a foreach loop.

String

$artikel = "This is some random text. I want to show you this image: [img alt=alt text for this image]the-image.gif[/img]";

So I have this regex used with preg_match_all to fetch the alt text and the image itself:

preg_match_all('/[img alt=(.*?)](.+?)[/img]/i', $artikel, $matches);

I can fetch the results individually by using print_r($matches[1]); and print_r($matches[2]);

The thing is that I can’t really figure out how to do a combined foreach loop. I would like to insert the image into my database with the associated alt text.

Something like this:

foreach ($matches as $match){
    //example code
    $stmt = $conn->prepare("INSERT INTO images (img_file, img_alt_text) VALUES (?, ?)");
    $stmt->bind_param("ss", $img_file, $img_alt_text);

    $img_alt_text = $match[1];
    $img_file = $match[2];
    $stmt->execute();
}

Advertisement

Answer

You can do that if you change the order in which the matches are returned. Use PREG_SET_ORDER and you will get them in a format that can be more easily iterated.

preg_match_all('/[img alt=(.*?)](.+?)[/img]/i', $artikel, $matches, PREG_SET_ORDER);

foreach ($matches as $match){
    //example code
    $stmt = $conn->prepare("INSERT INTO images (img_file, img_alt_text) VALUES (?, ?)");
    $stmt->bind_param("ss", $img_file, $img_alt_text);

    $img_alt_text = $match[1];
    $img_file = $match[2];
    $stmt->execute();
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement