在PHP中,如何保持img标签的样式属性

In PHP, how to keep style attributes for img tag

这是我的代码:

$pattern = '!<(img\s[^>]*?)>!is';
$html = '<img height="401" width="830" style="width:200px;height:150px" class="media-element file-default" typeof="Image" src="http://localhost.com/sites/default/files/sample_chart.png" alt="">';
$html = preg_replace_callback($pattern, 'custom_callback', $html);

在这段代码中,如何保持img标签的style属性

where style attributes comes at any where with img tag.我想保留它。

怎么样?

正则表达式 1: preg_replace("/(<img\s?)(.*)(style=\".*?\")(.*)(>)/i", "", $imageTag)

正则表达式 2: preg_replace("/<img.*(style=\".*?\").*>/i", "<img >", $imageTag)?

注意:我没有进行基准测试,但使用单个捕获组(第二个正则表达式)可能更有效。

在你的例子中:<img height="401" width="830" style="width:200px;height:150px" class="media-element file-default" typeof="Image" src="http://localhost.com/sites/default/files/sample_chart.png" alt="">

两个正则表达式 returns: <img style="width:200px;height:150px">

  1. 第 1 组:<img
  2. 未捕获:height="401" width="830"
  3. 第 2 组:style="width:200px;height:150px"(第二个正则表达式中的唯一组)
  4. 未捕获:class="media-element file-default" typeof="Image" src="http://localhost.com/sites/default/files/sample_chart.png" alt=""
  5. 第 3 组:>

解释正则表达式 1:

  1. (<img\s?):括号内为捕获组。匹配文字文本 <img 和一个可选的(问号表示 0 次或 1 次) space\s.
  2. .*:匹配任何字符(点)0次或更多次(星号)。
  3. (style=\".*?\"):括号内为捕获组。匹配文字文本 style=\"。您需要转义引号,因为您将在 PHP 中的字符串中使用正则表达式。尽可能少地匹配任何字符(点)0 次或更多次(星号)(量词后的问号)。由于星号 (*) 后跟一个问号 (?),因此它会在到达第一个引号 \".
  4. 时立即停止捕获字符
  5. .*:匹配任何字符(点)0次或更多次(星号)。
  6. (>): 捕获组结束

替换: </code> 用捕获组 1、2 和 3 替换文本并忽略其余部分</p> <p><strong>解释正则表达式 2</strong>:</p> <ol> <li><code><img.*:匹配文字文本<img和一个可选的(问号表示0次或1次)space\s后跟任何字符(星号) 0 次或多次(星星)。

2.(style=\".*?\"):括号内为捕获组。匹配文字文本 style=\"。您需要转义引号,因为您将在 PHP 中的字符串中使用正则表达式。尽可能少地匹配任何字符(点)0 次或更多次(星号)(量词后的问号)。由于星号 (*) 后跟一个问号 (?),因此它会在到达第一个引号 \".

时立即停止捕获字符
  1. .*>:尽可能多地匹配任何字符(点)(星号),直到到达标签的末尾 (>)。

替换<img > 将文本替换为文字 <img 后跟 space 单个捕获和结束符号标签。

测试https://www.functions-online.com/preg_replace.html

成功了