phppreg-replace

PHP - replace text and check for file?


I have this simple line of php

$text  = preg_replace("/\\ii(.*?)\\<>/", "<img scr='img/$1'>", $text);

Where I change II30.jpgII to <img scr='img/30.jpg'>, and it works fine.

But what I need, is to also check if there is a file called 30.txt, and if so, print the text below the image. I simply can't figure out how do do that - maybe I'm all wrong using preg_replace anyway?

What I acually need is a way to change \<img>30.jpg\<img> to <img scr='img/30.jpg'>, but I could not figure out how to search for \<img> so ended up using II instead :-)

And then call a function image_text_print("img/30.txt"), if the file exists, insert the return just below the image.

It not so well explained, but I hope you understand what I look for :-)


Edit

Instead maybe I should somehow search the $text for xxxxx, and then

But I can't figure out how to search for content between multiple and , in $text :-/

Jorgensen


Solution

  • This is my proposed solution using preg_match_all instead of preg_replace or preg_replace_callback. I have made a couple of assumptions: 1) The images are always digits followed by dot jpg, and 2) There may be other text in between the images. I'm sure you can adjust those as required.

    //sample text to search and replace on
    $text = 'Some other text \<img>30.jpg\<img> something in between \<img>50.jpg\<img> something else \<img>40.jpg\<img>';
    
    //initialize an array to hold the matches
    $matches = [];
    
    //this is here to mock up the function you said you needed to call
    //this code simply fetches the file contents
    function image_text_print($filename)
    {
      return file_get_contents($filename);
    }
    
    //find all matches of \<img>30.jpg\<img> where 30 can be any number made up of 1 or more digits (adjust the regex to your requirements)
    if(preg_match_all('#\\\<img>(\d+).jpg\\\<img>#', $text,$matches))
    {
      //preg_match_all gives us 2 arrays, one with the matched text and one with the image numbers
      foreach($matches[0] as $matchInd=>$matchText)
      {
        //build up the replacement text
        $replacement = '<img scr="img/'.$matches[1][$matchInd].'.jpg">';
        
        //create the filename and then check if it exists
        $filename = 'img/'.$matches[1][$matchInd].'.txt';
        if(is_file($filename))
        {
          //if the file exists call your function and append results
          $replacement .= image_text_print($filename);
        }
    
        //finally replace the matched text
        $text = str_replace($matchText,$replacement,$text);
      }
    }