php preg_split error when switching from split to preg_split

耗尽温柔 提交于 2019-12-07 08:00:34

问题


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!


回答1:


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

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



回答2:


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



回答3:


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()



来源:https://stackoverflow.com/questions/2288188/php-preg-split-error-when-switching-from-split-to-preg-split

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!