如何從字串中移除換行符並用一個空格替換? 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 瀏覽量

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.