您好,我有一个非常简单的代码
<a href="'.$aProfileInfo['Website'].'" target="_self">
<div class="callButton">Website</div>
</a>
问题在于,如果用户没有输入 http://,那么链接将指向我的网站而不是外部网站。
我该如何在 PHP 中检查用户是否未输入 http:// 并在缺少时自动添加它?
您好,我有一个非常简单的代码
<a href="'.$aProfileInfo['Website'].'" target="_self">
<div class="callButton">Website</div>
</a>
问题在于,如果用户没有输入 http://,那么链接将指向我的网站而不是外部网站。
我该如何在 PHP 中检查用户是否未输入 http:// 并在缺少时自动添加它?
我认为你最好使用内置函数parse_url()
,它会返回一个带有URL各个组成部分的关联数组
像这样做可以满足你的需求:
if ( $ret = parse_url($url) ) {
if ( !isset($ret["scheme"]) )
{
$url = "http://{$url}";
}
}
http
替换为 //
,以使用当前页面的协议(http / https)。 - Jose Philip Raja我个人使用这个,它部分地来自于php文档
$scheme = parse_url($link, PHP_URL_SCHEME);
if (empty($scheme))
$link = 'https://' . ltrim($link, '/');
一个简单的解决方案,可能不适用于所有情况(即包含“https://”的情况):
if (strpos($aProfileInfo['Website'],'http://') === false){
$aProfileInfo['Website'] = 'http://'.$aProfileInfo['Website'];
}
strpos
不是要求先提供 haystack,再提供 needle 吗? - Kevin Jipreg_replace('/^(?!https?:\/\/)/', 'http://', $aProfileInfo['Website'])
<a href="'. preg_replace('/^(?!https?:\/\/)/', 'http://', $aProfileInfo['Website']).'" target="_self">
<div class="callButton">Website</div>
</a>
(parse_url($aProfileInfo['Website'], PHP_URL_SCHEME) ? '' : 'http://') . $aProfileInfo['Website']
parse_url($aProfileInfo['Website'], PHP_URL_SCHEME)
判断链接中是否存在方案。然后使用三元运算符,如果找到方案,则输出''
,否则输出'http://'
。然后将链接附加在其后面。<a href="'.((parse_url($aProfileInfo['Website'], PHP_URL_SCHEME) ? '' : 'http://') . $aProfileInfo['Website']).'" target="_self">
<div class="callButton">Website</div>
</a>
https://
,但是对于相对 URL(如 //www.example.com
)无法正常工作。它还会在 ftp://
或其他协议前添加 http://
。请尝试使用以下代码替代:preg_replace('/^\/\/|^(?!https?:)(?!ftps?:)/', 'http://', $src)
(注意:如果不需要 ftp,则可以删除 ftp 的检查)。 - dhaupin您可以使用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'];
}
if (preg_match('/^https?:\/\//', $aProfileInfo['Website']) === 0) {
$aProfileInfo['Website'] = 'http://'.$aProfileInfo['Website'];
}
如果在字符串中没有找到数组中的任何内容,您可以使用此函数作为通用函数将某些内容附加到字符串末尾。
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;
}
像这样的吗?
if (!strpos($aProfileInfo['Website'], 'http://')) {
$aProfileInfo['Website'] = 'http://' . $aProfileInfo['Website'];
}
我相信David的答案是正确的方法,但也可以简化为:
parse_url($aProfileInfo['Website'], PHP_URL_SCHEME)==''?'http://'.$aProfileInfo['Website']:$aProfileInfo['Website']
这里是另一个与字符串减法相关的例子:
$changeLink = $myRow->site_url;
if(substr($changeLink, 0, 7) != 'http://') {
$changeLink = 'http://' . $changeLink;
}
// ....
echo "<a href=\"" . $changeLink . "\" target=\"_blank\"></a>";