यहाँ, हमने एक फ़ंक्शन सेट किया है जो एक स्ट्रिंग में "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
व्याख्या: रेगुलर एक्सप्रेशन ~^(?:f|ht)tps?://~i जांचता है कि स्ट्रिंग https://, https://, ftp://, या ftps:// से शुरू होती है या नहीं। i फ्लैग केस-इनसेंसिटिव मिलान बनाता है। यदि नहीं मिलता, तो "https://" प्रीपेंड करता है।
आधुनिक विकल्प (PHP 8+): str_starts_with() का उपयोग करें:
if (!str_starts_with($url, 'https://') && !str_starts_with($url, 'https://')) {
$url = 'https://' . $url;
}