Please tell me how to create a regular expression for preg_replace, so that when you save the reference type

<img src="img/image.jpg" title="desc" alt="titles" widht="200" height="100" /> 

link modified in

 <span itemprop="image" itemscope itemtype="https://schema.org/ImageObject"> <img itemprop="url" itemprop="image" class="class" title="desc" src="img/image.jpg" alt="" width="200" height="100" /> <meta itemprop="width" content="200"> <meta itemprop="height" content="100"> </span> 

I forgot to clarify the images contained in the text, and you need to return the string with the text

    2 answers 2

    I would break it down into elements, and would not write one regular schedule, if I need to, of course, I can write one, but in that case there will be difficulties when making edits or code failure.

    This example can be tested on http://phptester.net/

     <?php $str = '<img src="img/image.jpg" title="desc" alt="titles" width="200" height="100" />'; $src = preg_replace('/.*src="(.*?)".*$/','$1',$str); $title = preg_replace('/.*title="(.*?)".*$/','$1',$str); $alt = preg_replace('/.*alt="(.*?)".*$/','$1',$str); $width = preg_replace('/.*width="(.*?)".*$/','$1',$str); $height = preg_replace('/.*height="(.*?)".*$/','$1',$str); echo '<span itemprop="image" itemscope itemtype="https://schema.org/ImageObject"> <img itemprop="url" itemprop="image" class="class" title="'.$title.'" src="'.$src.'" alt="'.$alt.'" width="'.$width.'" height="'.$height.'" /> <meta itemprop="width" content="'.$width.'"> <meta itemprop="height" content="'.$height.'"></span>'; 
    • Forgot to clarify, the image is contained in the text, and you need to return the line back - Dikkiy
    • And if several images in the text? - Dikkiy
    • then you need to describe with one regular update with a global replacement, but in that case you need to have all the properties img go in the same order, otherwise the regular schedule will fly out - sivik_xes

    And I would prefer not to use regulars in this case. You can get all the attributes separately:

     $s = '<img src="img/image.jpg" title="desc" alt="titles" widht="200" height="100" />'; $domDocument = new DOMDocument(); $domDocument->loadHTML($s); $elements = $domDocument->getElementsByTagName('img'); $img = $elements->item(0); $title = $img->getAttribute('title'); $width = $img->getAttribute('width'); $height = $img->getAttribute('height'); $src = $img->getAttribute('src'); 

    And then beautifully insert them:

     <span itemprop="image" itemscope itemtype="https://schema.org/ImageObject"> <img itemprop="url" itemprop="image" class="class" title="<?=$title?>" src="<?=$src?>" alt="" width="<?=$width?>" height="<?=$height?>" /> <meta itemprop="width" content="<?=$width?>"> <meta itemprop="height" content="<?=$height?>"> </span>