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


Making sure string doesn't contain http(s) nor doesn't start with a forward slash

我正在尝试将根网址附加到重定向网址,但前提是它不包含httphttps并且不/开头

我有这段代码似乎有效:

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

但我想知道我不应该使用 AND 而不是使用 | 字符OR - 但我不确定如何在正则表达式中?

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

^(https?:/)?/

在代码中:

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

正则表达式演示

只需将您的正则表达式更改为,

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

演示

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

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