PHP正则表达式将html img标签替换为[img]


PHP Regular Expression to replace html img tag with [IMG]

我使用以下正则表达式将html img标记替换为[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">

感谢您的帮助

尽管Pekka说您应该使用HTML解析器是正确的(我完全同意),但出于教育目的,您可以使用'optional'字符?,它将前一个字符标记为可选:

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

注意'''?。我们转义反斜杠和问号(用反斜杠),然后说'这个字符是可选的'。

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

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

Shai .

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

http://simplehtmldom.sourceforge.net/

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

那么我们可以在

下面输入replace img tag步骤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."
}

STEP 2 then we will do replace in for loop

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
}

步骤3然后将数组转换为字符串

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

之后你会得到最终输出如下所示

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