Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP ลบบรรทัดใหม่จากสตริงและแทนที่ด้วย space เดียว

สมมติสตริงของเรามีบรรทัดใหม่

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

เราต้องการลบบรรทัดใหม่ข้างต้นและแทนที่ด้วย whitespace นั่นคือเอาต์พุทควรเป็น -

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.