php-regex-img标记匹配
如何从所有img标签中删除所有新行。例如,如果我有:php-regex-img标记匹配,php,regex,Php,Regex,如何从所有img标签中删除所有新行。例如,如果我有: $string = '<img src="somelong pathimage.jpg" height="1" width="10">'; $string=''; 所以看起来: $string = '<img src="somelongpathimage.jpg" height="1" width="10">'; $string=''; 谢
$string = '<img
src="somelong
pathimage.jpg"
height="1" width="10">';
$string='';
所以看起来:
$string = '<img src="somelongpathimage.jpg" height="1" width="10">';
$string='';
谢谢,因为每个操作系统的换行符都有不同的ASCII字符:
windows=\r\n
unix=\n
mac=\r
$string=str\u replace(数组(“\r\n”、“\r”、“\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);
}
$string=“\n\n我的介绍和结束前的另一个\n\n”;
打印$string;
打印trim\u img\u标签($string);
函数修剪\u img\u标记($string){
$tokens=preg_split('/(和结束前的另一个
之后:
<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>
我的介绍和另一个结束前
当然preg\u replace
在这方面太过了?strr($str,array(“\n”=>”,\r“=>”)
?@Jon-你完全正确-太过了,但我喜欢正则表达式。在这种情况下,str\u replace就足够了。@zzbov-strtrt()显然比str\u replace慢-但它看起来确实像一个很酷的替代方法,您可以删除“\r\n”
,因为“\r”
和“\n”
无论如何都将转换为空字符串。
<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>