tags:

views:

46

answers:

2

What are the differences pros/cons of using either '/' or '#' as the regex encapsulation

e.g.

'/' = preg_match('/MYSEARCH}(.+)ENDMYSEARCH/s',$out,$matches);

'#' = preg_match('#MYSEARCH}(.+)ENDMYSEARCH#s',$out,$matches);

Thanks!

+7  A: 

The only thing that matters to PHP / PCRE is that you must use the same character at the beginning and at the end.

What matters to you is escaping : inside the regex, you have to escape the delimiter if you want to use it.

For instance, to match a part of an URL, using / as a delimiter, you regex might look like this :

'/^http:\/\/www/'

Using / as delimiter, you have to escape the slashes which are inside the regex -- not easy, and not looking well.

On the other hand, using # as delimiter :

'#http://www#'

Much more easier to write and read, isn't it ?


Depeding on your need and/or preference, you can use whatever character you want -- I sometimes see '!' or '~', for instance.

Pascal MARTIN
Thanks thats really helpful!
Lizard
Wasn't aware you could use a character of your preference, and I thought I had learned what was to be learned of PHP Regexs.
MitMaro
@Lizard : you're welcome :-) ;; @MitMaro : there is always more than what you think, with PCRE ;-)
Pascal MARTIN
Personally I use backtick ` It's rarely used inside my regexps.
Kamil Szot
+1  A: 

Also remember that with preg_quote you can add the delimiter to be escaped.

OIS