PHP replace text in variable
$image
开发者_如何学运维 variable gives this code (when echo
is used):
<img src="/image.png" width="100" height="147" alt="" class="some_class" />
width
,height
,src
andclass
attributes can be different.
What should we do:
- remove
width
andheight
from$image
- replace
alt=""
withalt="Poster"
Thanks.
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.
$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);
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"/>
will also replace <embed width="x">
which is wrong. We need to catch only with <img>
tag
精彩评论