Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_split error when switching from split to preg_split

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!

like image 939
benjisail Avatar asked Feb 18 '10 11:02

benjisail


2 Answers

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

$statements = preg_split("/\s*;\s*/", $content);
like image 119
Ben James Avatar answered Oct 23 '22 05:10

Ben James


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

Similar to the way strings are delimited by quotation marks, regular expressions in many languages, such as Perl or JavaScript, are delimited by forward slashes. This will lead to expressions looking 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
like image 39
Álvaro González Avatar answered Oct 23 '22 04:10

Álvaro González