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

更新於: 10 月 12 日,2020 年

414 次瀏覽

開啟你的 職業

完成本課程並獲得認證

入門
廣告