7

Is there a utility that will convert POSIX to PCRE for PHP? I'm somewhat confused by the PHP manual on PCRE, and while I'll try to find more info on PCRE, I was wondering if anyone had designed such a utility.

Or, if anyone would explain how to convert the following, that would also be fine:

ereg("^#[01-9A-F]{6}$", $sColor)

But please explain how it's done, not just tell me the conversion.

waiwai933
  • 14,133
  • 21
  • 62
  • 86

3 Answers3

6

preg_match("/^#[01-9A-F]{6}$/", $sColor)
In this case you only need to add the two delimiters.

In perl you can write something like

if ( s =~ /x.+y/ )
{ print "match"; }
As you can see the actual regular expression is encapsulated in //. If you want to set an option on the regular expression you put it after the second /, e.g. switching the expression to ungreedy by default /x.+y/U
pcre now emulates this behaviour. Though you have to call a function you also have to provide the delimiters and set the options after the second delimiter. In perl the delimiter has to be /, with pcre you can chose more freely
preg_match("/^#[01-9A-F]{6}$/", $sColor)
preg_match("!^#[01-9A-F]{6}$!", $sColor)
preg_match("#^\#[01-9A-F]{6}$#", $sColor) // need to escape the # within the expression here
preg_match("^#[01-9A-F]{6}$", $sColor)
all the same to pcre, best to chose a character that doesn't appear within the expression.
VolkerK
  • 95,432
  • 20
  • 163
  • 226
4

preg_match("/^#[01-9A-F]{6}$/D", $sColor)

Note the D modifier. People forget about it all the time. Without it $ will allow a final newline character. A string like "#000000\n" would pass. This is a subtle difference between POSIX and PCRE.

And, of course, [01-9] can be rewritten to [0-9].

Geert
  • 1,804
  • 15
  • 15
-1

By the way, PHP supports both PCRE and POSIX regular expressions. Here is the section of the PHP manual on POSIX regular expressions, so you don't have to convert them: http://www.php.net/manual/en/book.regex.php

newacct
  • 119,665
  • 29
  • 163
  • 224
  • 2
    I'm aware about this. However, POSIX will be deprecated in PHP 5.3, so I was looking to just keep everything up-to-date. – waiwai933 Jun 21 '09 at 05:18
  • This answer is outdated, could you update it? `ereg()` is deprecated now – HamZa May 08 '14 at 21:41