1

I want to remove specific image from string.

I need to remove Image with specific width and height.

I have tried this, but this will remove first image.

$description = preg_replace('/<img.*?>/', '123', $description, 1); 

I want to remove any/all image(s) with specific width and height.
E.g. Remove this image <img width="1" height="1" ..../>

Emil
  • 7,220
  • 17
  • 76
  • 135
Jasmeen
  • 876
  • 9
  • 16
  • From the [docs](http://php.net/manual/en/function.preg-replace.php): `preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )`, you are setting a limit of 1 to your preg_replace. However, with that code you will be removing *all* images, do you really just want a particular subset of images removed? – alxgb Jan 08 '15 at 11:35
  • Yes, I want to remove particular images only. Not all. – Jasmeen Jan 08 '15 at 11:38

3 Answers3

0

Made a little example for you

<?php

$string = 'something something <img src="test.jpg" width="10" height="10" /> and something .. and <img src="test.jpg" width="10" height="10" /> and more and more and more';
preg_match_all('~<img(.+?)width="10"(.+?)height="10"(.+?)/>~is', $string, $return);

foreach ($return[0] as $image) {
    $string = str_replace($image, '', $string);
}

echo $string;
Peter
  • 8,776
  • 6
  • 62
  • 95
0

I suggest that you move away from using regex expressions to parse (or manipulate) HTML, because it's not a good idea, and here's a great SO answer on why.

For example, by using Peter's approach (preg_match_all('~<img src="(.+?)" width="(.+?)">~is', $content, $return);), you are assuming that all your images start with <img, are followed by the src, and then contain the width=, all typed exactly like that and with those exact whitespace separations, and those particular quotes. That means that you will not capture any of these perfectly valid HTML images that you want to remove:

<img src='asd' width="123"> <img src="asd" width="123"> <img src="asd" class='abc' width="123"> <img src="asd" width = "123">

While it's of course perfectly possible to catch all these cases, do you really want to go through all that effort? Why reinvent the wheel when you can just parse the HTML with already-existing tools. Take a look at this other question.

Community
  • 1
  • 1
alxgb
  • 543
  • 8
  • 18
0

I got the solution:

$description = preg_replace('!<img.*?width="1".*?/>!i', '', $description);
fivedigit
  • 18,464
  • 6
  • 54
  • 58
Jasmeen
  • 876
  • 9
  • 16