如果 URL 中不存在 http://,如何添加它?
这里,我们设置了一个函数,该函数向字符串中添加 "http://。假设我们传递了以下值 −
example.com
我们想要的输出是使用 "http://" 的,即一个实际的链接 −
http://example.com
为此,可以使用 dot(.) 符号和 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP