3

I am making a system that takes all optional subjects from a education and puts it in a database. This works fine.
Now I want to make sure if you choose "Finance A" you can't choose "Finance C", I'm trying to do this with preg_replace as the subject is a array. But it keeps giving me an error:

Delimiter must not be alphanumeric or backslash

Now here is some of the code:

if
(
    preg_replace("/" + $name_without_level + " (A|B|C)/", "", $andre_fag) 
        == $andre_fag
    || preg_replace("/" + $name_without_level + " (A|B|C)/", "", $andre_fag2)
        == $andre_fag2
){

The variable $name_without_level gives the Subject name without A, B or C, the Level.

How to fix the error? I have tried everything I can think of.

2
  • You need to add error handling to your code. In case of an error, you should show to yourself the regex that failed. Then you will see what's wrong. In any case you should add to your question what $name_without_level is. Commented Oct 15, 2011 at 9:50
  • 1
    Does "here is some of the code:" mean that's not the code line mentioned in the error message? Because if even there was a bare / in your variable, that pcre error wouldn't match. Commented Oct 15, 2011 at 9:55

1 Answer 1

2

Imagine $name_without_level is just "Finance / Markets". Imagine what happens to your regular expression.

Use preg_quoteDocs to ensure you're looking for the right string literally and you don't destroy your regular expression:

$pattern = sprintf('/%s (A|B|C)/', preg_quote($name_without_level));
if
(
    preg_replace($pattern, "", $andre_fag) == $andre_fag
    || preg_replace($pattern, "", $andre_fag2) == $andre_fag2
){

This does not mean that this is your only problem with the code. You need to do error checking to actually locate the error.

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

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.