使用 php preg_replace 将 alt="20x20" 替换为 style="width:20;height:20;"

use php preg_replace to replace alt="20x20" with style="width:20;height:20;"

如何使用phppreg_replace解析一串HTML并替换

alt="20x20"style="width:20;height:20;"

感谢任何帮助。

我试过了。

$pattern = '/(<img.*) alt="(\d+)x(\d+)"(.*style=")(.*)$/';
$style = 'width:px;height:px;';
$text = preg_replace($pattern, $style, $text);

如评论中所述,您应该使用 DOM 来操作 HTML 代码。 如果您想通过 preg_replace 执行此操作,我建议您在 this one.

等网站的帮助下自行找出正则表达式

您不需要 preg_replace 来执行此操作。您可以使用 str_replace

$html = '<img alt="20x20" />';

preg_match('/<img.*?alt="(.*?)".*>/',$html,$match);

$search = 'alt="' . $match[1] . '"';

list($width, $height) = explode('x', $match[1]);

if(is_numeric($width) && is_numeric($height))
{
    $replace = 'style="width:' . $width . 'px;height:' . $height . 'px;"';
    echo str_replace($search, $replace, $html);
}

输出:

<img style="width:20px;height:20px;">

如果你坚持使用正则表达式来改变 HTML 标记,你无疑会在某个时候卡住,此时你最好看看 Python 之类的东西soup,或者可能是 goode olde tidy 库,我认为它包含在 PHP 规范中。但现在:

  <?php
      $originalString = 'Your string containing <img src="xyz.png" alt="20x20">';
      $patternToFind = '/alt="20x20"/i';
      $replacementString = 'style="width:20;height:20;"';
      preg_replace($patternToFind, $replacementString, $originalString);
 ?>

由于似乎很多人都对代码请求感到非常恼火,您可以查看此 link 以获取 php.net 的指导。在解释 PHP 的构造时并不总是那么清楚,但在这种情况下可以轻松解决您的问题: http://php.net/manual/en/function.preg-replace.php