确保字符串不包含http(s),也不以正斜杠开头

时间:2014-09-18 07:32:57

标签: php regex preg-match

我正在尝试将根网址附加到重定向网址,但只有在它不包含httphttps 不包含时才会以 /开始。

我有出现的代码:

$redirect_url = '/foo';

if (!preg_match('#https?://|^/#', $redirect_url)) {
    $redirect_url = 'http://' . $redirect_url;
}

但我想知道不应该使用|的{​​{1}}字符,我不应该使用OR - 但我不确定如何使用正则表达式?

3 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式避免使用|

^(https?:/)?/

在代码中:

if (!preg_match('#^(https?:/)?/#', $redirect_url)) {
    $redirect_url = 'http://' . $redirect_url;
}

RegEx Demo

答案 1 :(得分:1)

只需将正则表达式更改为

即可
if (!preg_match('#^(?:https?://|/)#', $redirect_url)) {
    $redirect_url = 'http://' . $redirect_url;
}

DEMO

答案 2 :(得分:1)

不确定我理解你的需要,但这是你想要的吗?

if (preg_match('#(?!.*https?://)(?!^/)#', $redirect_url)) {
    $redirect_url = 'http://' . $redirect_url;
}