从 HTML 字符串中的多行 <img> 标记中删除多余的换行符/空格

问题描述 投票:0回答:3

如何从所有 img 标签中删除所有新行。例如,如果我有:

$string = '<img
           src="somelong
            pathimage.jpg"
             height="1" width="10">';

所以它看起来像:

$string = '<img src="somelongpathimage.jpg" height="1" width="10">';
php regex image multiline sanitization
3个回答
2
投票

因为每个操作系统都有不同的 ASCII 字符用于换行:
窗户 =
UNIX =
麦克=

$string = str_replace(array("\r\n", "\r", "\n"), "", $string);

主题链接:http://www.php.net/manual/en/function.nl2br.php#73440


0
投票
$string = preg_replace("/\n/" , "" , $string);

0
投票

如果您确实想保留除了 img 标签的内容之外的所有内容,则代码会有点膨胀:

$string = "<html>\n<body>\nmy intro and <img\n src='somelong\npathimage.jpg'\n height='1'   width='10'> and another <img\n src='somelong\npathimage.jpg'\n height='1' width='10'> before end\n</body>\n</html>";
print $string;
print trim_img_tags($string);

function trim_img_tags($string) {
  $tokens = preg_split('/(<img.*?>)/s', $string, 0, PREG_SPLIT_DELIM_CAPTURE);
  for ($i=1; $i<sizeof($tokens); $i=$i+2) {
    $tokens[$i] = preg_replace("/(\n|\r)/", "", $tokens[$i]);
  }
  return implode('', $tokens);
}

之前:

<html>
<body>
my intro and <img
 src='somelong
pathimage.jpg'
 height='1' width='10'> and another <img
 src='somelong
pathimage.jpg'
 height='1' width='10'> before end
</body>
</html>

之后:

<html>
<body>
my intro and <img src='somelongpathimage.jpg' height='1' width='10'> and another <img src='somelongpathimage.jpg' height='1' width='10'> before end
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.