如何从所有 img 标签中删除所有新行。例如,如果我有:
$string = '<img
src="somelong
pathimage.jpg"
height="1" width="10">';
所以它看起来像:
$string = '<img src="somelongpathimage.jpg" height="1" width="10">';
因为每个操作系统都有不同的 ASCII 字符用于换行:
窗户 =
UNIX =
麦克=
$string = str_replace(array("\r\n", "\r", "\n"), "", $string);
$string = preg_replace("/\n/" , "" , $string);
如果您确实想保留除了 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>