如果 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