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'/>"
CodePudding user response:
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'>'
CodePudding user response:
A javascript method to extract the tag :
Only possible when there is only one
tag
and no extra<
>
Can use any string extracter likesubstring
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>
CodePudding user response:
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);