php 丢失时为 URL 添加 http:// 前缀

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6240414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:44:49  来源:igfitidea点击:

Add http:// prefix to URL when missing

phphttphtmlanchorhref

提问by DiegoP.

Hello I have a very simple code

你好我有一个非常简单的代码

<a href="'.$aProfileInfo['Website'].'" target="_self">
    <div class="callButton">Website</div>
</a>

The problem is that if the user does not enter http:// the link will then point to my website and not to the external website as it should.

问题是,如果用户没有输入 http:// 链接将指向我的网站,而不是它应该指向的外部网站。

How do I check in PHP if the user has not entered http:// and automatically add it when it is not there?

如果用户没有输入 http:// 并在它不存在时自动添加它,我如何检查 PHP?

采纳答案by Christopher Armstrong

A simple solution which may not work in all cases (i.e. 'https://'):

一个可能不适用于所有情况的简单解决方案(即“https://”):

if (strpos($aProfileInfo['Website'],'http://') === false){
    $aProfileInfo['Website'] = 'http://'.$aProfileInfo['Website'];
}

回答by David

I think you'd better use the built in function parse_url()which returns an associative array with its components

我认为你最好使用内置函数parse_url(),它返回一个关联数组及其组件

something like this will work for you:

这样的事情对你有用:

 if  ( $ret = parse_url($url) ) {

      if ( !isset($ret["scheme"]) )
       {
       $url = "http://{$url}";
       }
}

回答by Satbir Kira

I personally use this, which is partially taken from php docs

我个人使用这个,它部分取自 php docs

$scheme = parse_url($link, PHP_URL_SCHEME);
if (empty($scheme)) {
    $link = 'http://' . ltrim($link, '/');
}

回答by Evan Kennedy

There are two ways of tackling this problem: url parsing and regular expressions.

有两种方法可以解决这个问题:url 解析和正则表达式。

Some will say url parsing is right, but regular expressions work just as well in this case. I like being able to have simple one-liners for things like this especially because this would be a common occurrence in template files where you may need a one-liner inside an echo statement to maintain readability.

有些人会说 url 解析是正确的,但正则表达式在这种情况下也能正常工作。我喜欢能够为这样的事情使用简单的单行,特别是因为这在模板文件中很常见,在这种情况下,您可能需要在 echo 语句中使用单行来保持可读性。

Regular Expressions

常用表达

We can do this in a single function call with preg_replace.

我们可以使用preg_replace在单个函数调用中完成此操作。

preg_replace('/^(?!https?:\/\/)/', 'http://', $aProfileInfo['Website'])

This uses a negative lookaheadat the beginning of the string that looks for http://or https://. If either are found, the replace doesn't happen. If they aren'tfound, it replaces the beginning of the string (0 characters) with http://essentially prepending this to the string without modifying it.

negative lookahead在查找http://or的字符串开头使用 a https://。如果找到其中之一,则不会发生替换。如果他们没有找到,它会替换字符串(0字符)与年初http://基本前面加上这个字符串,而无需修改它。

In context:

在上下文中:

<a href="'. preg_replace('/^(?!https?:\/\/)/', 'http://', $aProfileInfo['Website']).'" target="_self">
    <div class="callButton">Website</div>
</a>

URL Parsing

网址解析

(parse_url($aProfileInfo['Website'], PHP_URL_SCHEME) ? '' : 'http://') . $aProfileInfo['Website']

What this does is find out if a scheme is present on the link throught parse_url($aProfileInfo['Website'], PHP_URL_SCHEME). Then using a ternary operator, it will either output ''if there was one found or 'http://'if one wasn't found. Then it appends the link onto that.

这样做的目的是通过 找出链接上是否存在方案parse_url($aProfileInfo['Website'], PHP_URL_SCHEME)。然后使用三元运算符,''如果找到或未找到,它将输出'http://'。然后它将链接附加到该链接上。

In context:

在上下文中:

<a href="'.((parse_url($aProfileInfo['Website'], PHP_URL_SCHEME) ? '' : 'http://') . $aProfileInfo['Website']).'" target="_self">
    <div class="callButton">Website</div>
</a>

回答by kevinji

You could use strpos:

你可以使用strpos

// Trim trailing whitespace
$aProfileInfo['Website'] = trim($aProfileInfo['Website']);

// Test if the string begins with "http://"
if (strpos($aProfileInfo['Website'], 'http://') !== 0) {
  $aProfileInfo['Website'] = 'http://' . $aProfileInfo['Website'];
}

回答by Hailwood

You can use this function as a general if nothing from the array is found in the stringappend something to it.

如果在字符串中未找到数组中的任何内容,则可以将此函数用作一般函数。

function httpify($link, $append = 'http://', $allowed = array('http://', 'https://')){

  $found = false;
  foreach($allowed as $protocol)
    if(strpos($link, $protocol) !== 0)
      $found = true;

  if($found)
    return $link;
  return $append.$link;
}

回答by ggonzal

You also may take into account that "http(s)" must be at the beginning of the url:

您还可以考虑到“http(s)”必须位于 url 的开头:

if (preg_match('/^https?:\/\//', $aProfileInfo['Website']) === 0) {
    $aProfileInfo['Website'] = 'http://'.$aProfileInfo['Website'];
}

回答by Porta Shqipe

Here is another example with string subtraction:

这是字符串减法的另一个示例:

$changeLink = $myRow->site_url;
  if(substr($changeLink, 0, 7) != 'http://') {
     $changeLink = 'http://' . $changeLink;  
}

// ....

// ....

echo "<a href=\"" . $changeLink . "\" target=\"_blank\"></a>";

回答by Nate

I believe David's answeris the proper way to do this, but it can be simplified like this:

我相信大卫的回答是正确的方法,但可以像这样简化:

parse_url($aProfileInfo['Website'], PHP_URL_SCHEME)==''?'http://'.$aProfileInfo['Website']:$aProfileInfo['Website']

回答by gpresland

Something like this?

像这样的东西?

if (!strpos($aProfileInfo['Website'], 'http://')) {
    $aProfileInfo['Website'] = 'http://' . $aProfileInfo['Website'];
}