0

I have a string that is for a blog, potentially it could have an unlimited number of images in this string, what I am trying to do is get all of the src="" and add a prefix to the url and use it as the hyperlink.

My string:

$test = 'Hello world
<img src="images/image1.jpg" />Line 2
<img src="images/image2.jpg" />Some text 
<img src="images/image3.jpg" />';

I am able to prefix href. I am able to achieve this:

<a href="images/image1.jpg"><img src="images/image1.jpg" /></a>
<a href="images/image1.jpg"><img src="images/image2.jpg" /></a>
<a href="images/image1.jpg"><img src="images/image3.jpg" /></a>

This is my code so far:

 $new = preg_replace('/(<img[^>]+src="([^\\"]+)"[^>]+\\/>)/','<a href="\\2">\\1</a>',$test2);
    echo $new;

I need to add foldername/as prefix in all the image src. What im trying to turn this into is the following:

<a href="images/image1.jpg"><img src="foldername/images/image1.jpg" /></a>
<a href="images/image1.jpg"><img src="foldername/images/image2.jpg" /></a>
<a href="images/image1.jpg"><img src="foldername/images/image3.jpg" /></a>

How can I do that?

halfer
  • 19,824
  • 17
  • 99
  • 186
user2828442
  • 2,415
  • 7
  • 57
  • 105
  • You only want a regex solution? Im not verse on regex. However i could offer u a solution, just wouldnt be regex. – GetSet Feb 01 '20 at 09:47
  • will work for me, please share – user2828442 Feb 01 '20 at 09:51
  • Try this preg_replace('/()/','$1',$test2) – Aman Rawat Feb 01 '20 at 09:52
  • Does that @AmanRawat extract the image url from the source to put into the href and modify the `src` url? – GetSet Feb 01 '20 at 09:53
  • Edited my comment and added a foledername to the href – Aman Rawat Feb 01 '20 at 09:57
  • @AmanRawat, please don't post answers as comments as it gets clogged up. Also you are adding the foldername to the `` tag and not the `` tag. – Nigel Ren Feb 01 '20 at 10:02
  • i need to prefix in img src not in href @AmanRawat – user2828442 Feb 01 '20 at 10:03
  • @NigelRen Drafting my answer, just confirming that the solution is working for him or not – Aman Rawat Feb 01 '20 at 10:04
  • @GetSet , i need prefix in image src , i can handle href but again repeating, i need in image src – user2828442 Feb 01 '20 at 10:04
  • @user2828442 I posted a way to gather an array of image urls – GetSet Feb 01 '20 at 10:32
  • Note that we prefer a technical style of writing here. We gently discourage greetings, hope-you-can-helps, thanks, advance thanks, notes of appreciation, regards, kind regards, signatures, please-can-you-helps, chatty material and abbreviated txtspk, pleading, how long you've been stuck, voting advice, meta commentary, etc. Just explain your problem, and show what you've tried, what you expected, and what actually happened. – halfer Feb 01 '20 at 11:55
  • Hi user2828442. In this question I have removed a quote block that is not a quote, and removed chatty material that is not necessary (see comment above). There is an expectation here that when an experienced editor improves a question, further questions do not replicate the same problems. Since I have made these sorts of edits on your posts before, I am downvoting on this occasion, as a helpful reminder. – halfer Feb 01 '20 at 11:57

2 Answers2

3

To do this using DOMDocument rather than regex (a good reason is https://stackoverflow.com/a/1732454/1213708).

The code loads the HTML and then looks for all of the <img> tags. It first takes the value of src and adds the extra part to it. Then it creates a new <a> tag and also adds the (original) src value as the href attribute. It then replaces the <img> tag with the <a>, but adds the old value back into the <a>...

$dom = new DOMDocument();
$dom->loadHTML($test, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

foreach ( $dom->getElementsByTagName("img") as $image ) {
    $src = $image->getAttribute("src");
    $image->setAttribute("src", "foldername/".$src);
    $anchor = $dom->createElement("a");
    $anchor->setAttribute("href", $src);
    $image->parentNode->replaceChild($anchor, $image);
    $anchor->appendChild($image);
}

echo $dom->saveHTML();
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

Not that it matters now, but here is a parsing solution without regex. I prefer @NigelRen solution actually now that its posted. However, here is a way to build a list of image urls without regex that could be used for solving your issue and provide further exploration. I haven't tested the code but i'm pretty fair on it working.

<?php

$html = 'some html here';

$sentinel = '<img src="';

$quoteSentinel = '"';

$done = false;

$offset = 0;

$imageURLS = array();

while (!$done) {

    $nextImageTagPos = strpos($html, $sentinel, $offset);

    if ($nextImageTagPos !== false) {

        //*** Parsing

        // Find first quote

        $quoteBegins = false;

        for ($i = $nextImageTagPos; $i < $nextImageTagPos + 100; $i++) {
            if (substr($html, $i, 1) == $quoteSentinel) {
                $quoteBegins = $i;
                break;
            }
        }

        // Find ending quote

        $quoteEnds = false;

        if ($quoteBegins !== false) {
            for ($i = $quoteBegins + 1; $i < $quoteBegins + 1000; $i++) {
                if (substr($html, $i, 1) == $quoteSentinel) {
                    $quoteEnds = $i;
                    break;
                }
            }

            if ($quoteEnds !== false) {

                // Hooray! now we are getting somewhere

                $imgUrlLength = ($quoteEnds - $quoteBegins) - 1;

                $imgUrl = substr($html, $quoteBegins + 1, $imgUrlLength);

                // ***Requirements

                /*
                I have a string that is for a blog, potentially it could have an unlimited number of images in this string, what i am trying to do is get all of the src="" and add a prefix to the url and use it as the hyperlink.
                */

                // But for brevity lets skip requirements and build an array of URLs.

                $imageURLS[] = $imgUrl;

                $offset = $quoteEnds + 1;




            }

        }

        // Extract url

    }
    else {
        $done = true;
    }


}   
Aman Rawat
  • 2,625
  • 1
  • 25
  • 40
GetSet
  • 1,511
  • 2
  • 10
  • 13