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

PHP เพิ่ม http:// หากไม่มีใน URL

ที่นี่เราสร้างฟังก์ชันที่เพิ่ม "https://" เข้าไปในสตริง สมมติว่าส่งค่าดังนี้

example.com

และต้องการผลลัพธ์พร้อม "https://" คือลิงก์จริง

https://example.com

สำหรับกรณีนี้ สามารถใช้การต่อสตริงด้วยจุด (.) และตรวจสอบเงื่อนไขด้วย preg_match()

ตัวอย่างโค้ด

<!DOCTYPE html> <body> <?php function addingTheHTTPValue($stringValue) { if (!preg_match("~^(?:f|ht)tps?://~i", $stringValue)) { $stringValue = "https://" . $stringValue; } return $stringValue; } echo addingTheHTTPValue("example.com"); echo "<br>"; echo addingTheHTTPValue("https://example.com"); ?> </body> </html>

ผลลัพธ์

https://example.com https://example.com