PHP RegEx允许mailto:http://和tel:超链接

时间:2015-04-16 14:11:34

标签: php regex laravel

我需要做的是允许文本字段验证并允许mailto:http://或tel:类型的URL。

我使用的是PHP 5(和Laravel 4,但与本帖不相关)。

我一直在谷歌搜索一段时间,但我似乎无法得到一个表达式允许所有三种类型的匹配。我尝试了一些冗长复杂的字符串,还有一些非常简短的字符串,它只返回false。

这是我的最新消息:

mailto:([^\?]*)|http:([^\?]*)|tel:([^\?]*)

解决方案:

由于我使用的是Laravel 4,我决定使用parse_url函数而不是正则表达式。也就是说,还提供了一些其他很好的解决方案。

我的最终验证函数:

    Validator::extend('any_url', function($attribute, $value)
    {
        $allowed = ['mailto', 'http', 'https', 'tel'];
        $parsed = parse_url($value);

        return in_array($parsed['scheme'], $allowed);
    });

4 个答案:

答案 0 :(得分:3)

您可以使用parse_urlscheme。然后检查它是否在['mailto', 'http', 'https','tel']

之内

答案 1 :(得分:1)

试试这个:

((mailto:\w+)|(tel:\w+)|(http://\w+)).+

http://regexr.com/3ar2c

答案 2 :(得分:0)

您需要将整个正则表达式置于捕获分组中,//之后还需要http:

mailto:([^\?]*)|(http://([^\?]*))|(tel:([^\?]*))

因为在你的正则表达式中,pip的工作方式不同:

mailto:     #first
([^\?]*)|http: #second
([^\?]*)|tel:  #third
([^\?]*)       #fourth

答案 3 :(得分:0)

你可能需要这个:

/^((?:tel|https?|mailto):.*?)$/

示例:

 $strings  = array("http://www.me.com", "mailto:hey@there.nyc", "tel:951261412", "hyyy://www.me.com");

foreach($strings as $string){

if (preg_match('/^((?:tel|https?|mailto):.*?)$/im', $string)) {
    echo $string ."\n";
}else{
echo "No Match for : $string \n";
}
}

DEMO PHP
DEMO REGEX

<强>说明

^((?:tel|https?|mailto):.*?)$
-----------------------------

Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed) «^»
Match the regex below and capture its match into backreference number 1 «((?:tel|https?|mailto):.*?)»
   Match the regular expression below «(?:tel|https?|mailto)»
      Match this alternative (attempting the next alternative only if this one fails) «tel»
         Match the character string “tel” literally (case insensitive) «tel»
      Or match this alternative (attempting the next alternative only if this one fails) «https?»
         Match the character string “http” literally (case insensitive) «http»
         Match the character “s” literally (case insensitive) «s?»
            Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
      Or match this alternative (the entire group fails if this one fails to match) «mailto»
         Match the character string “mailto” literally (case insensitive) «mailto»
   Match the character “:” literally «:»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) (line feed) «$»