Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "~" in regex? [duplicate]

Tags:

regex

php

Possible Duplicate:
Tilde operator in Regular expressions

echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');

The code is from http://php.net/manual/en/functions.anonymous.php

I searched for what "~" is in regex and did not find an answer.

What does it do?

like image 225
Michael Avatar asked Jan 28 '13 16:01

Michael


2 Answers

The first and last character of a regular expression in PHP (and other implementations) is known as the delimiter. Normally, you see a / being used, but in this case, someone chose ~. Read more here.

Not sure why ~ was chosen though; probably a habit of that particular developer. Normally, one chooses a different delimiter over / when the regular expression itself will contain slashes (e.g. matching URLs), so that slashes don't need to be escaped every time.

like image 169
slackwing Avatar answered Sep 19 '22 22:09

slackwing


The symbol ~ is just used as delimiter in PHP regexps.

like image 42
zavg Avatar answered Sep 22 '22 22:09

zavg