$a = 'asdasdasd as asdasdas <img src="http://www.domain1.com/1.gif"> sdfsdf <img src="http://www.domain2.com/1.gif">  <img src="http://www.domain3.com/1.gif">';

$pattern = '(<img[^>]+domain1.com[^>]+>)';
$a = preg_replace($pattern, '', $a);

How can I keep only img tags from domain1.com?

Any idea for an inverse like
$pattern = '!(<img[>]+domain1.com[>]+>)';

    $string=..
    preg_match_all('/(<img etc src="([^"]+))" etc/i',$string,$a);
    //note how the refrences are stored..
    echo '<pre>';
    print_r($a);
    for($i=0;$i<count($a[0]); $i++){
       //loop through and between the references, you should be able to do a exact string_replace().. 
    }
    
    

      Another way to do it is by

      1. Choosing temporary character replacements for < and >, for example [ and ]
      (and you could go with just one substitution character for both < and >)
      
      2. Substituting the chosen characters with their html entitites, for example & #91; and & #93;
      (without the whitespace between & and # - editor replaces these entities with their characters)
      
      3. preg_replacing img elements that have domain.com in the src attribute with
      < and > replaced by the chars in 1, e.g. [img src="http://www.domain.com/1.gif" /]
      
      Do note that some care has to be taken with the pattern if you want to prevent this
      to slip through: http://otherdomain.com/domain.com/1.gif
      
      4. remove all other img elements, for example preg_replace('#<img[^>]+>#', '', $string)
      
      5. replace all occurences of [img ... /] back into <img ... />
      

        regardless of how you do this, you are essentially looking for "something" (a src= attribute) inside of "something else" (an <img> tag). If you'll think about if from this perspective, you'll be able to write code as portable as possible in case you ever need to add to the "something" or the "something else" list..

        preg_replace|preg_match offers the best way to do this and do the replacements because of its back-referencing capability.

          Write a Reply...