假设以下是带有新行的字符串
$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.