59

I want to know what's the meaning of tilde operator in regular expressions.

I have this statement:

if (!preg_match('~^\d{10}$~', $_POST['isbn'])) {
    $warnings[] = 'ISBN should be 10 digits';
}

I found this document explaining what tilde means: ~

It said that =~ is a perl operator that means run this variable against this regular expression.

But why does my regular expression contains two tilde operators?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
Keira Nighly
  • 15,326
  • 8
  • 29
  • 28

2 Answers2

74

In this case, it's just being used as a delimiter.

Generally, in PHP, the first and last characters of a regular expression are "delimiters" to mark the start and ending position of a matching portion (in case you want to add modifiers at the end, like ungreedy, etc)

Generally PHP works this out from the first character in a string that is meant as a regular expression, matching the second occurence of it as the second delimiter. This is useful where you have an occurrence of the normal delimiter in the text (for example, occurences of / in the text) - this means you don't have to do awkward things.

Matching for "//" with the delimiter set to "/"

/\/\//

Matching for "//" with the delimiter of "#"

#//#

Mez
  • 24,430
  • 14
  • 71
  • 93
  • 4
    ic, I'm used to the / delimiter so I was a little confused with the ~ delimiter. Thanks for clarifying. – Keira Nighly Jun 02 '09 at 06:19
  • This does only apply to PCRE http://docs.php.net/manual/en/book.pcre.php and not POSIX ERE http://docs.php.net/manual/en/book.regex.php – Gumbo Jun 02 '09 at 11:47
8

In this case, it doesn't mean anything. It is simply delimiting the start and end of your pattern. In PCRE (Perl Compatible Regular Expressions), which is what you're using with preg_* in PHP, the pattern is input along side the expression options, like so:

preg_match("/pattern/opt", ...);

However, the use of "/" as the delimiter in this case is arbitrary - although forward slash is popular, it can be replaced with anything. In your case, it's tilde.

Nick
  • 1,799
  • 13
  • 13
  • Oh, Ok.. I got the regular expression from the book.. They didn't explain what it meant. So was confused a little. I was just trying to clarify things because I'm confused. Thanks! – Keira Nighly Jun 02 '09 at 06:21
  • 1
    '/' is popular because it's the standard delimiter for perl regular expressions, which is what preg stands for ;) – Matthew Scharley Jun 02 '09 at 06:28