5

The person who designed this database decided to make a multi-value column for "subjects" with each value written like an ordered list, i.e. "1. [subject] 2. [another subject] 3. [a third subject]" etc. I want to make an array of every subject used, so I need to split these values into distinct subjects.

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

When I run this, I get a Warning: preg_split() [function.preg-split]: Unknown modifier '+'.

What am I doing wrong?

1
  • Delimiters? surround the regex with /'s Commented Mar 8, 2011 at 20:01

4 Answers 4

15

You forgot the delimiters:

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

Also, slap that guy. Hard.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you everyone! My mistakes are always silly like this. And I would consider physical violence, but it was probably an intern that left years ago.
+1 also for slapping. I hate when people set up columns like this. Way to completely fail at basic relational database design.
1

You're missing the pattern delimeters so php thinks [ ] are it.

Use e.g.

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

Comments

1

In PHP, PCREs need delimiters. The most common one used is /, but you can also use another character:

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

You get this warning because PHP treats [] as delimiters.

This will give you an array like:

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

so you'd have to remove the first item ( unset($subjects[0]) ).


Depending on the possible inputs, using preg_match_all might be better:

$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.

where $matches is

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

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

)

1 Comment

I wouldn't say "PHP regular expressions" because the POSIX family of functions don't need them.
0

You should write your regex with delimiters in order to avoid this error:

/[0-9]+\.\s/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.