PHP regex: what is a "class at offset 0"?

I am trying to remove all punctuation from a string using a simple regular expression and the php preg_replace function, although I get the following error:

Compilation error: classes named POSIX are only supported inside the class with offset 0

I suppose this means that I cannot use classes named POSIX outside the class with offset 0. My question is: what does it mean when it says β€œinside the class with offset 0”?

$string = "I like: perl"; if (eregi('[[:punct:]]', $string)) $new = preg_replace('[[:punct:]]', ' ', $string); echo $new; 
+25
php regex
Jan 24 '09 at 0:13
source share
4 answers

preg_* functions expect Perl-compatible regular expressions with delimiters. So try the following:

 preg_replace('/[[:punct:]]/', ' ', $string) 
+39
Jan 24 '09 at 0:20
source share

NOTE. The g modifier is not required with the PHP PCRE implementation!

In addition to the Gumbo answer , use the g modifier to replace all punctuation events:

 preg_replace('/[[:punct:]]/g', ' ', $string) // ^ 

From Jonathan Lonowski (see comments):

 > [The g modifier] means "Global" -- ie, find all existing matches. Without it, regex functions will stop searching after the first match. 
+5
Jan 24 '09 at 0:24
source share

Explanation of why you get this error: PCRE uses Perl to determine what the delimiter is. Your outer [] looks like valid delimiters, causing it to read [:punct:] as part of the regular expression.

(Oh, and avoid ereg functions if you can - they will not be included in PHP 5.3.)

0
Jan 24 '09 at 0:30
source share

I just added g to regexp, as suggested in one of the underders, it did the opposite of the expected wahts and did NOT filter punctuation, it turns out that preg_replace does not require g, since it is global / recursive in the first place

0
Jan 24 '09 at 0:56
source share



All Articles