What is ~ in regular expression for?

Asked

Viewed 149 times

5

I have the code:

function addhttp($url){

    if(!preg_match('~^(http)s?://~i', $url)){

        $url = 'http://'.$url;
    }

    return $url;

}

It adds HTTP if the given URL does not contain, but what I’m doubtful about is the question of ~ which has at the beginning and then at the end ~i . I wonder what this is for

1 answer

3


PCRE(Perl Compatible Regular Expressions) regular expressions require delimiters which are a pair of non-alphanumeric characters where one stands at the beginning and the other at the end. It is also common to use the bar / as delimiter in case your regex needs to capture some you need to escape it.

 '~^(http)s?://~i    <---- modificador PCRE
--^           ^----
inicio         fim

The letter i or any other after the demilitar is one of the PCRE modifiers, the i means that the expression will be analyzed as case insensitive or does not differentiate capital from minuscules that would be the equivalent of [a-zA-Z].

  • Same goes for ~i ?

  • @Alissonacioli O i is a flag used to indicate that the comparison should be case-insensitive, that is to say, nay Differentiates uppercase and lowercase.

  • I get it... I tried to do it like this /^(http s)?:/// and made a mistake because of / . So use ~ ?

  • That’s the only way: /^(http)s?: //i

  • You need to escape the bar if it doesn’t understand that you closed and opened two regexs. @Alissonacioli

  • Understood. Thank you both very much!! @rray

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.