从字符串中删除换行符并用一个空格替换,PHP 可以做到吗?
phpserver side programmingprogramming更新于 2025/8/18 1:37:17
假设以下字符串包含换行符
$sentence = " My name is John Smith My Favorite subject is PHP. ";
我们需要删除上面的换行符并用空格替换,即输出应为 −
My name is John Smith My Favourite subject is PHP.
为此,请使用 trim() 并在其中使用 preg_replace() 进行替换。
示例
PHP 代码如下
<!DOCTYPE html>
<html>
<body>
<?php
$sentence = "
My name is John Smith
My Favorite subject is PHP.
";
$sentence = trim(preg_replace('/\s\s+/', ' ', $sentence));
echo $sentence;
?>
</body>
</html>
输出
这将产生以下输出 −
My name is John Smith My Favorite subject is PHP.

