ที่นี่ เราได้ตั้งค่าฟังก์ชันที่เพิ่ม "http:// ให้กับสตริง สมมติว่าเราได้ส่งผ่านค่าต่อไปนี้แล้ว -
example.com
และผลลัพธ์ที่เราต้องการคือ "http://" นั่นคือลิงก์จริง −
http://example.com
สำหรับสิ่งนี้ คุณสามารถใช้เครื่องหมายจุด (.) และการจับคู่แบบมีเงื่อนไขกับ preg_match()
ตัวอย่าง
<!DOCTYPE html>
<body>
<?php
function addingTheHTTPValue($stringValue) {
if (!preg_match("~^(?:f|ht)tps?://~i", $stringValue)) {
$stringValue = "http://" . $stringValue;
}
return $stringValue;
}
echo addingTheHTTPValue("example.com");
echo "<br>";
echo addingTheHTTPValue("https://example.com");
?>
</body>
</html> ผลลัพธ์
http://example.com https://example.com