php - 正则表达式img标签匹配

时间:2011-03-21 19:05:22

标签: php regex

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

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

所以它看起来像:

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

由于

3 个答案:

答案 0 :(得分:2)

因为每个操作系统都有不同的ASCII字符用于换行:
windows = \ r \ n
unix = \ n
mac = \ r

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

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

答案 1 :(得分:0)

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

答案 2 :(得分: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>