8

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?

Community
  • 1
  • 1
Michael
  • 4,786
  • 11
  • 45
  • 68
  • 1
    It appears to be using `~` as a delimiter instead of `/` which is most commonly used. – datasage Jan 28 '13 at 17:01
  • Well, I looked into some refs/tuts regarding regex too and did not find any. Then I searched for "~" while I did't know how the symbol is called exactly. I guess there are a lot of people performing this kind of search.. – Michael Jan 28 '13 at 17:09
  • I believe you still get the rep if the question is closed, so no worries. – Evan Davis Jan 28 '13 at 17:10
  • Of course, no problem.. I was just saying. – Michael Jan 28 '13 at 17:13
  • The other question doesn't have the symbol `~` in its question text. I don't know if SO's search engine searches symbols as keywords but if so, then this question could still be helpful. – Andrew Cheong Jan 28 '13 at 17:15
  • Yup, I mentioned that people might seach for that and while on page the first big H1 contains the symbol, it is a SEO way to get people faster to the answer.. – Michael Jan 28 '13 at 17:17

2 Answers2

12

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.

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
2

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

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
zavg
  • 10,351
  • 4
  • 44
  • 67