views:

488

answers:

2

Hi,

I get this warning from php after the change from split to preg_split for php 5.3 compatibility :

PHP Warning:  preg_split(): Delimiter must not be alphanumeric or backslash

the php code is :

$statements = preg_split("\\s*;\\s*", $content);

How can I fix the regex to not use anymore \

Thanks!

+4  A: 

The error is because you need a delimiter character around your regular expression.

$statements = preg_split("/\s*;\s*/", $content);
Ben James
+2  A: 

Although the question was tagged as answered two minutes after being asked, I'd like to add some information for the records.

In many languages (such as Perl or JavaScript) regular expressions are delimited by forward slashes, the same that strings are delimited by quotes. So you cab have stuff like this:

/\s*;\s*/

This syntax also allows to specify modifiers:

/\s*;\s*/Ui

PHP's Perl-compatible regular expressions (aka preg_... functions) inherit this. However, PHP itself doesn't support this syntax so feeding preg_split() with /\s*;\s*/ would raise a parse error. Instead, you enclose it with quotes to build a regular string.

One more thing you must take into account is that PHP allows to change the delimiter. For instance, you can use this:

@\s*;\s*@Ui

What is it good for? It simplifies the use of forward slashes inside the expression since you don't need to escape them. Compare:

/^\/home\/.*$/i
@^/home/.*$@i
Álvaro G. Vicario