正则表达式问题(对于preg_split)

时间:2011-03-08 19:59:01

标签: php regex

设计此数据库的人决定为“主题”创建一个多值列,每个值都写成有序列表,即“1. [subject] 2. [another subject] 3. [第三主题] “等等。我想制作一个使用过的每个主题的数组,所以我需要将这些值分成不同的主题。

$subjects = preg_split("[0-9]+\.\s", $subject);

当我运行时,我得到警告: preg_split()[function.preg-split]:未知修饰符'+'。

我做错了什么?

4 个答案:

答案 0 :(得分:11)

你忘记了分隔符:

$subjects = preg_split("/[0-9]+\.\s/", $subject);

另外,打那个家伙。硬。

答案 1 :(得分:1)

你错过了pattern delimeters所以php认为[ ]就是这样。

使用例如

$subjects = preg_split("~[0-9]+\.s~", $subject);

答案 2 :(得分:1)

在PHP中,PCRE需要delimiters。最常用的是/,但您也可以使用其他字符:

preg_split('/[0-9]+\.\s/', $subject);
//          ^          ^

您收到此警告是因为PHP将[]视为分隔符。

这将为您提供如下数组:

Array
(
    [0] => 
    [1] => [subject] 
    [2] => [another subject] 
    [3] => [a third subject]
)

因此您必须删除第一项(unset($subjects[0]))。


根据可能的输入,使用preg_match_all可能会更好:

$str = "1. [subject] 2. [another subject] 3. [a third subject]";

preg_match_all('/\[([^\]]+)\]/', $str, $matches); 

$subjects = $matches[1];
// or $subject = $matches[0]; if you want to include the brackets.

其中$matches

Array
(
    [0] => Array
        (
            [0] => [subject]
            [1] => [another subject]
            [2] => [a third subject]
        )

    [1] => Array
        (
            [0] => subject
            [1] => another subject
            [2] => a third subject
        )

)

答案 3 :(得分:0)

您应该使用分隔符编写正则表达式,以避免此错误:

/[0-9]+\.\s/
相关问题