2011-03-21 85 views
0

如何從所有img標籤中刪除所有新行。因此,舉例來說,如果我有:php - 正則表達式img標籤匹配

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

所以看起來:

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

感謝

回答

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

當然,'preg_replace'對於這個過度了嗎? – Jon 2011-03-21 19:09:52

+0

'strtr($ str,array(「\ n」=>'',「\ r」=>''))'? – zzzzBov 2011-03-21 19:54:02

+0

@Jon - 你說的沒錯 - 這是矯枉過正,但我​​喜歡正則表達式。在這種情況下,str_replace就足夠了。 @zzzzBov - strtr()顯然比str_replace慢 - 但它看起來像一個很酷的替代方案http://net-beta.net/ubench/index.php?t=strtr2 – Duniyadnd 2011-03-21 19:57:54

2

因爲每個操作系統有斷行不同的ASCII字符:
窗口= \ 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

+2

你可以放棄'「\ r \ n 「',因爲'\ r」'*和*'「\ n」'無論如何都會被轉換爲空字符串。 – zzzzBov 2011-03-21 19:55:15

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> 

After:

<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>