-2

I have a string that contains an <img> tag somewhere in text entered by users. I want to get rid of all the text but keep the image tag but I have no idea how to do that, is it possible?

$str = "<img src= 'imagepath'/> Lorem ipsum dolor sit amet, consectetur adipiscing elit" 

What I want it to do is only keep the and get rid of all the other text and instead look like this:

$str = "<img src='imagepath'/>"
mplungjan
  • 169,008
  • 28
  • 173
  • 236
lochness
  • 49
  • 5

3 Answers3

0

Here a solution with to capture < to >

$regex = '/<.*?\>/m';
$str = "<img src='imagepath'> Lorem ipsum dolor sit amet, consectetur adipiscing elit";

preg_match($regex, $str, $result);

var_dump($result[0]);

Output is '<img src='imagepath'>'

Dylan Delobel
  • 786
  • 10
  • 26
0

A javascript method to extract the tag :

Only possible when there is only one tag and no extra < >
Can use any string extracter like substring substr ....

var str = "<img src= 'imagepath'/> Lorem ipsum dolor sit amet, consectetur adipiscing elit"

function trimTagOut() {
  var index1 = str.indexOf("<")
  var index2 = str.indexOf(">")
  var slicedTag = str.slice(index1, index2+1) 
  document.getElementById("demo").innerHTML = slicedTag;
}
<button onclick="trimTagOut()">Trim tag</button>
<div id="demo"></div>
Rana
  • 2,500
  • 2
  • 7
  • 28
0

with the help of string manipulation, you can do this with PHP by following method.

$str = "<img src= 'imagepath'/> Lorem ipsum dolor sit amet, consectetur adipiscing elit";
$start=strpos($str, '<');
$end=strpos($str, '/>');
$img=substr($str, $start, $end-$start+1);
Noman Shaikh
  • 139
  • 2
  • 14