views:

69

answers:

3

$image variable gives this code (when echo is used):

<img src="/image.png" width="100" height="147" alt="" class="some_class" />
  • width, height, src and class attributes can be different.

What should we do:

  1. remove width and height from $image
  2. replace alt="" with alt="Poster"

Thanks.

+1  A: 

If the attributes can be variable, then your best choice for working with the HTML is to use a library that actually understands HTML, like DOM.

$dom = new DOMDocument;
$dom->loadXML($variable);
$dom->documentElement->removeAttribute('width');
$dom->documentElement->removeAttribute('height');
$dom->documentElement->setAttribute('alt', 'poster');
echo $dom->saveXML($dom->documentElement);

outputs:

<img src="http://site.com/image.png" alt="poster"/>
Gordon
Thanks Gordon! 1) with and height can be different. 2) replacement for alt doesn't work
Happy
I'd suggest `'width="100" height="147" alt=""'` since there are going to be 2 alt's after your solution.
DrColossos
+1  A: 
$pattern = '/alt="" width="\d+" height="\d+"/i';
$replacement = 'alt="Poster"';
$variable = preg_replace($pattern, $replacement, $variable);

fix to work with any order of attributes(Gordon's comment):

$pattern = '/alt=""/i';
$replacement = 'alt="Poster"';
$variable = preg_replace($pattern, $replacement, $variable);
$pattern = '/width="\d+"/i';
$replacement = '';
$variable = preg_replace($pattern, $replacement, $variable);
$pattern = '/height="\d+"/i';
$replacement = '';
$variable = preg_replace($pattern, $replacement, $variable);
kgb
this assumes the attributes will always appear in that order.
Gordon
what if the attributes appear with more whitespace inbetween e.g. `alt = "" width= "100" height= "147"`?
Gordon
+1  A: 

I'd use regular expressions to do this.

// Replace width="..." and height="..." with nothing
$variable = preg_replace('/(width|height)\s*=\s*"[^"]*"/i', '', $image);

// Replace alt="..." with alt="Poster"
$variable = preg_replace('/alt\s*=\s*"[^"]*"/i', 'alt="Poster"', $variable);

This method is not dependant on the order of the attributes, which of the some other answers are. Also note that the second regular expressions will replace alt="<any string here>" with alt="Poster". It should be easy enough to change it to only replace alt="" though.

tomit
Thanks man, this works!
Happy