Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Xóa dòng mới (new lines) từ chuỗi và thay bằng một khoảng trắng trong PHP

Giả sử chuỗi có dòng mới:

$sentence = " My name is John Smith My Favorite subject is PHP. ";

Cần xóa dòng mới và thay bằng khoảng trắng - kết quả:

My name is John Smith My Favourite subject is PHP.

Dùng trim() bên ngoài preg_replace() để thay thế.

Ví dụ

<!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>

Kết quả

My name is John Smith My Favorite subject is PHP.