【问题标题】:preg_replace img tag in sequence in PHP在PHP中按顺序preg_replace img标签
【发布时间】:2026-01-02 14:00:01
【问题描述】:

我有一个内容,就像

Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test

我想改成

Test test test &lt;id&gt;1&lt;/id&gt; test test &lt;id&gt;2&lt;/id&gt; test test

我试过了:

preg_match_all('/<img(.*?)alt=\"(.*?)\"(.*?)>/si', $content, $result, PREG_SET_ORDER);
foreach($result as $val) {                
          $content = preg_replace('/<img(.*?)alt=\"(.*?)\"(.*?)>/si', '<id>'.$val[2].'</id>', $content);

但它给了我:

Test test test <id>2</id> test test <id>2</id> test test

【问题讨论】:

标签: php regex preg-replace preg-match-all


【解决方案1】:

您在 foreach 中的替换存在问题。这是固定版本。

<?php

$str = <<<term
Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test'
term;

preg_match_all('/<img.*?alt=[\'"](\d+)[\'"]>/', $str, $matches, PREG_SET_ORDER, 0);

foreach($matches as $val) {                
    $str = preg_replace('/<img.*?alt=[\'"](' . $val[1] . ')[\'"]>/', '<id>'.$val[1].'</id>', $str);
}

var_dump($str);

在这里查看: http://sandbox.onlinephpfunctions.com/code/ad70f171ec5387451a29166865474de0f223f7c1

【讨论】:

    【解决方案2】:

    似乎 preg_match* 不是在这里使用的正确函数,需要循环证明了这一点。只需一个 preg_replace() 即可完成:

    preg_replace("/&lt;.*? alt=[\"']([0-9]+)[\"'] *&gt;/", '&lt;id&gt;${1}&lt;/id&gt;', $teststr);

    这将独立地对每个匹配的表达式进行操作,并一次性完成所有操作。如果您确定确实需要 src 值,则可以根据需要调整表达式。

    【讨论】:

      【解决方案3】:

      试试这个。

          $data = `Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test`;
      
          $replace = ["<img src='abc.png' alt='1'>","<img src='123.png' alt='2'>"];
          $value = ["<id>1</id>","<id>2</id>"];
      
          $dataNeeded = str_replace($replace, $value, $emailContent);
      
      echo $dataNeeded;
      

      【讨论】:

      • 用2个数组替换多个数据的值。
      • $replace 字符串不会相同。这取决于用户的输入。