
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add HTTP to URL in PHP
Here, we have set a function that adds "http:// to a string. Let’s say we have passed the following value −
example.com
And the output we want is with "https://" i.e. an actual link −
http://example.com
For this, you can use dot(.) notation and conditional match with preg_match().
Example
<!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>
Output
http://example.com https://example.com
Advertisements