Question

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!

Was it helpful?

Solution

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

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

OTHER TIPS

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

If you don't like delimiters, you can use T-Regx tool:

pattern("\\s*;\\s*")->split($content):

You can also use Pattern::of("\\s*;\\s*")->split()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top