【问题标题】:PHP Regular Expression to replace html img tag with [IMG]PHP正则表达式用[IMG]替换html img标签
【发布时间】:2011-11-20 07:21:39
【问题描述】:

我有以下正则表达式用 [IMG] 替换 html img 标签;

echo preg_replace('/(^<img) (.*) (>$)/i', '[IMG]', $subject);

它在一定程度上按预期工作,但是我正在使用的一些 img 标签以“/>”结尾,一些以“>”结尾。我无法让上述内容与后者一起使用。

样本 1(作品):

<img src="image-1.gif" alt="image-1" width="175>" height="80" />

示例 2(不起作用)

<img src="image-2.gif" width="77" height="51" alt="image-2">

感谢您的帮助。

【问题讨论】:

  • 这就是为什么正则表达式不是解析 PHP 的最佳选择。考虑改用 HTML 解析器。 Best methods to parse HTML with PHP
  • 样本 1 是故意损坏 HTML 还是您的意思是 ...width="175" height="80" /&gt;

标签: php html regex image


【解决方案1】:

虽然 Pekka 说您应该使用 HTML 解析器是正确的(我完全同意),但为了教育起见,您可以使用“可选”字符 ?,它将前一个字符标记为可选:

echo preg_replace('/(^<img) (.*)(\\\?>$)/i', '[IMG]', $subject);

通知\\\?。我们转义反斜杠和问题 marl(带有反斜杠),然后说“这个字符是可选的”。

【讨论】:

  • 我的错,需要额外的逃生。现在可以使用了。
【解决方案2】:

我建议获取 URL,然后手动编写 [IMG] 标签。

例如

preg_match('/src="(.*?)"/', '<img src="image-2.gif" width="77" height="51" alt="image-2">', $matches)
echo '[IMG]'.$matches[1].'[/IMG]';

夏。

【讨论】:

    【解决方案3】:

    我会尝试使用 DOM 解析器。它们更可靠。

    http://simplehtmldom.sourceforge.net/

    【讨论】:

    【解决方案4】:

    例如我们有这样的字符串:- $str = 'Text &lt;img src="hello.png" &gt; hello &lt;img src="bye.png" /&gt; other text.

    那么我们可以像下面这样替换img标签

    第 1 步

    $str = 'Text <img src="hello.png" > hello <img src="bye.png" /> other text.';
    if(preg_match("/(<img .*>)/i", $str)){
         $img_array = preg_split('/(<img .*>)/i', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
    }
    

    这将输出:

    array(5) {
      [0]=>
      string(5) "Text "
      [1]=>
      string(22) "<img src="hello.png" >"
      [2]=>
      string(7) " hello "
      [3]=>
      string(21) "<img src="bye.png" />"
      [4]=>
      string(12) " other text."
    }
    

    步骤 2 然后我们将在 for 循环中进行替换

    for ($i = 0; $i < count($img_array); $i++){
         $url = "welcome.png";
         $img_array[$i] = preg_replace('/(<img .*>)/i', '<img src="'.$url.'" alt="'.$url.'">', $img_array[$i]); //replace src path & alt text
    }
    

    STEP 3 然后在将数组转换为字符串之后

    $str = implode('', $img_array);
    

    然后你会得到最终输出这样的

    $str = 'Text <img src="welcome.png" > hello <img src="welcome.png" /> other text.';
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      相关资源
      最近更新 更多