Home > Software design >  Get multiple values from preg_match_all and use of foreach
Get multiple values from preg_match_all and use of foreach

Time:10-01

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();
}

CodePudding user response:

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();
}

CodePudding user response:

I presume there won't always be an alt for each image (if there are - just iterate over each pair (say by index % 2 condition inside loop).

I suggest you to process the $article string in two stages:

  1. Find all images (say with your entire pattern in parentheses)
  2. Then: iterate over results and find submatches with your exact pattern.
  • Related