0

I am getting strings from the database which can have URLs of some images. But I don't want the user to see the URL written over there but the actual image. I've tried searching on google and stackoverflow but the answers which I am getting are either not relevant or hard to understand.

for example

$string= "hello everyone check this picture: http://somesite.com/heretheimage.jpg";

after:

$new_string = "hello everyone check this picture: <img src='http://somesite.com/heretheimage.jpg'>";

how can I do this in php?

EDIT : Some one marked this questions as possible duplicate of Regular expression pattern to match url with or without http://www . but I want to tell you that in that question user want to identify urls. but in my question it is particularly for image urls and then those urls should be enclosed in img tag.

prabhjot
  • 394
  • 2
  • 6
  • 16

1 Answers1

1

you can do so using preg_match function try this :

    <?php
    $string= "hello everyone check this picture: http://somesite.com/heretheimage.jpg";
    $pattern = '/(?:(?:https?:\/\/))[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/=]*(\.jpg|\.png|\.jpeg))/';
    preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
    $new_string = "hello everyone check this picture: <img src='".$matches."'>";
    ?>
M0ns1f
  • 2,705
  • 3
  • 15
  • 25