开发者

PHP replace text in variable

开发者 https://www.devze.com 2023-01-05 12:03 出处:网络
$image开发者_如何学运维 variable gives this code (when echo is used): <img src=\"/image.png\" width=\"100\" height=\"147\" alt=\"\" class=\"some_class\" />

$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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消