5

What does the "~" character mean in the following?:

preg_match_all("~<img [^>]+>~", $inputw, $output);

My guess is that they are beginning and end markers such as ^ and $.

Theramax
  • 195
  • 1
  • 13

3 Answers3

8

It is a delimiter

A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Nambi
  • 11,944
  • 3
  • 37
  • 49
4

As Nambi said you are free to choose the delimiter in a regex. However if the delimiter appears in the pattern it has to escaped. Knowing this, imagine the following situation

'/\/var\/www\/test/' # delimited with /
'~/var/www/test~' # delimited with ~

The last one does not require to escape the / as the delimiter is now ~. Much cleaner isn't it?

As a general guideline you are encouraged to choose a delimiter which isn't pattern of the pattern itself, I guess ~ is widely distributed as an alternative to / as it rarely appears in real world pattern.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • @Nambinarayanan's link says to that: If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability. ;) – loveNoHate Feb 07 '14 at 10:04
  • @dollarvar You know what they say about links – OGHaza Feb 07 '14 at 10:07
  • 1
    @dollarvar that it is better to include essential parts of the answer here on SO. I figured you were implying this answer is redundant because the link provided already says that, but I may well have been mistaken. – OGHaza Feb 07 '14 at 10:14
  • @dollarvar I'm with OGHaza here (otherwise I wouldn't gave the answer). I felt like it is ok to say 1 or 2 additional sentences here. – hek2mgl Feb 07 '14 at 10:18
  • @OGHaza Ah, no, have to take two things out of your comment: a) I may be confused, but do you say, the other answerer did not include enough? b) NO, I just gave the content of the link, because it FITTED and well supported the answer, but then he added more, and then it seemed, well redundant to post that, lol, should I delete the comment? – loveNoHate Feb 07 '14 at 10:29
  • @dollarvar It took me a while to get the intention of your comment.. no, it's fine :) – hek2mgl Feb 07 '14 at 18:37
  • I see, well it was twisted I guess perhaps neither he nor me (just) stated that it was the manual. :) – loveNoHate Feb 07 '14 at 19:15
0

The dirty little delimiter secret they don't tell you ->
http://uk.php.net/manual/en/regexp.reference.delimiters.php

Examples:

Paired delimiters (raw: \d{2}Some\{33\}\w{5})

{\d{2}Some\\{33\\}\w{5}} parses to \d{2}Some\\{33\\}\w{5} and
{\d{2}Some\{33\}\w{5}} parses to \d{2}Some{33}\w{5}

Un-Paired delimiters (raw: \d{2}Some\+33\+\w{5})

+\d{2}Some\+33\+\w{5}+ parses to \d{2}Some+33+\w{5} and
+\d{2}Some\\+33\\+\w{5}+ won't parse because the delimiter is un-escaped.