繁体   English   中英

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

[英]PHP RegEx to allow mailto: http:// and tel: hyperlinks

我需要做的是允许一个文本字段验证并允许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);
    });

您可以使用parse_url为您提供scheme 然后检查它是否在['mailto', 'http', 'https','tel']

尝试这个:

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

http://regexr.com/3ar2c

您需要将所有正则表达式放在捕获组中,也需要//http:

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

因为在您的正则表达式中,pip的作用不同:

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

您可能需要此:

/^((?: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";
}
}

演示PHP
演示正则表达式

说明:

^((?: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) «$»

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM