如果 PHP URL 中不存在 http://,如何添加?
phpserver side programmingprogramming更新于 2025/4/13 5:22:17
这里,我们设置了一个函数,将 "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

