$string = "
put returns between paragraphs
for linebreak add 2 spaces at end
";
想从字符串中删除所有新行。
我有这个正则表达式,它可以捕获所有的,问题是我不知道该用哪个函数来使用它。
/\r\n|\r|\n/
$string应该变成:
$string = "put returns between paragraphs for linebreak add 2 spaces at end ";
$string = "
put returns between paragraphs
for linebreak add 2 spaces at end
";
想从字符串中删除所有新行。
我有这个正则表达式,它可以捕获所有的,问题是我不知道该用哪个函数来使用它。
/\r\n|\r|\n/
$string应该变成:
$string = "put returns between paragraphs for linebreak add 2 spaces at end ";
当前回答
您可以删除新行和多个空白。
$pattern = '~[\r\n\s?]+~';
$name="test1 /
test1";
$name = preg_replace( $pattern, "$1 $2",$name);
echo $name;
其他回答
转义序列\R匹配通用换行符
也就是说,任何被Unicode视为换行序列的东西。这包括由\v(垂直空格)匹配的所有字符,以及多字符序列\x0D\x0A…
$string = preg_replace('/\R+/', " ", $string);
在8位非utf -8模式下\R相当于以下内容:(?>\ R \n|\n|\x0b|\f|\ R |\x85)…pcre.org
Regex101演示
我不确定这是否对已经提交的答案有任何价值,但我也可以张贴它。
// Create an array with the values you want to replace
$searches = array("\r", "\n", "\r\n");
// Replace the line breaks with a space
$string = str_replace($searches, " ", $string);
// Replace multiple spaces with one
$output = preg_replace('!\s+!', ' ', $string);
用这个:
将换行符替换为空字符串:
$string = preg_replace("/[\\n\\r]+/", "", $string);
或者你可能想用一个空格替换换行符:
$string = preg_replace("/[\\n\\r]+/", " ", $string);
对已接受答案的一些评论:
+表示“1或更多”。我认为你没有必要重复。我认为你可以简单地写“/\s+/”。
此外,如果想要删除字符串中的第一个和最后一个空白,则添加trim。
经过这些修改,代码将是:
$string = preg_replace('/\s+/', ' ', trim($string));
这个选项也会删除制表符
$string = preg_replace('~[\r\n\t]+~', '', $text);