如何从字符串中移除换行符并用一个空格替换? PHP


假设以下带换行符的字符串

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

更新日期:13-10-2020

695 浏览量

开启您的职业生涯

通过完成课程获得认证

开始
广告