I am trying to remove any user inserted image tags while allowing my own image icon. I have this
$post = 'Here is an image <img src="imgage.jpg" /> to check
and my icon <img src="/images/ImageLink.jpg" />';
$imgcheck = true;
$stringstart = 0;
while($imgcheck == 'true'){
if($stringstart = strpos($post,'<img',$stringstart)){
if ($stringend = strpos($post,'>',$stringstart)){
$strlength = $stringend - $stringstart;
$substring = substr($post,$stringstart,$strlength);
if (!preg_match('/src="\/images\/ImageLink.jpg"/',$substring)){
$post = str_replace($substring, "", $post);
}
else{
$stringstart = $stringend;
}
}
else{
$imgcheck = 'false';
}
}
else{
$imgcheck = 'false';
}
}
I would like this to return
Here is an image to check and my icon <img src="/images/ImageLink.jpg" />
I seem to be getting an error on one of the strpos functions but cannot figure out why.
Update:Thank you hakre. That answer is much more elegant. I did finally make the code work with
$imgcheck = true;
$stringstart = 0;
while($imgcheck == 'true'){
if($stringstart = strpos($post,'<img',$stringstart)){
if ($stringend = strpos($post,'>',$stringstart)){
$strlength = $stringend - $stringstart +4;
$substring = substr($post,$stringstart,$strlength);
if (!preg_match('~src="\/images\/ImageLink.jpg"~',$substring)){
$post = str_replace($substring, "", $post);
}
else{
$stringstart = $stringend;
}
}
else{
$imgcheck = 'false';
}
}
else{
$imgcheck = 'false';
}
}
with < and > used because I am using a div with contenteditable=true for user input. This could also be used for a text area by simply replacing < and > with <img and > respectively as well as changing
$strlength = $stringend - $stringstart +4;
to
$strlength = $stringend - $stringstart +1;
Thank you for your time.
You should use a HTML parser for the job, for example
DOMDocument.The following example code will put your html fragment into a div with the id
postso it can be identified:Then the
DOMDocumentis created and the html loaded into it. Additionally the container div is made available as a variable by it’s id:The next step is to select all images you want to remove. This is done with xpath. The xpatch expression will then be queried with the
$containeras reference:The next step is to iterate over all found elements and to remove them:
Finally the changed HTML needs to be aquired by taking everything out of the
$container:Now everything is in
which will give you:
Hope this is useful.