regex - invalid regular expression in PHP

914

I'm new to regular expressions. I wrote a pattern like below:

'A/[.]+;'.'B/[.0-9]+;'.'C/[0-9]+;'.'D/[.]+;'.'E/[.0-9]+;'.'F/[.a-zA-Z]+;';

which is meant to match strings such as

"A/U88;B/12.01.5;C/123456;D/4ND8;E/3.56.78;F/Sa.yA;"

But I got an error invalid Regular Expression.

What's wrong about this pattern?

265

Answer

Solution:

Your regex is not in good format. Amongst other erorrs you are not escaping the special character/ properly.

To escape special characters in a regex expression use the\ as a preceeding character. So to escape the/ character you would have to write\/.


In order to obtain the characters between each/ ; pair from the string:

$string = 'A/U88;B/12.01.5;C/123456;D/4ND8;E/3.56.78;F/Sa.yA;'

you can usepreg_match_all().

preg_match_all — Perform a global regular expression match

and set the flagPREG_PATTERN_ORDER.

PREG_PATTERN_ORDER Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

Now you can access the$matches[1] array which are the characters that matched the regular expression inside the parentheses().

more onpreg_match_all(): php.net/preg-match-all.


Here is a working example:

$string = 'A/U88;B/12.01.5;C/123456;D/4ND8;E/3.56.78;F/Sa.yA;';

// [A-F] accepts one upper case character from A-F
// [0-9]? accepts one number from 0-9, the ? means the number may or may not exist there
// ([^;]+) accepts one or more of any characters except semicolons
preg_match_all('/[A-F][0-9]?\/([^;]+);/', $string, $matches, PREG_PATTERN_ORDER);

print_r($matches[1]);

which outputs:

Array ( 
        [0] => U88 
        [1] => 12.01.5 
        [2] => 123456 
        [3] => 4ND8 
        [4] => 3.56.78 
        [5] => Sa.yA
      )
571

Answer

Solution:

I don't know what that string mean or what you are trying to do, but your regex did have some synthax error in it. First of all, you need to escape the/. Second, I couldn't make it work, so I built one that matches your stirng. I don't know if the order of the letter is important or not.
[ABCDEF](\/)([A-Z0-9.]+);

Here is a working Regex101 with your regex. https://regex101.com/r/jXUqav/1

People are also looking for solutions to the problem: javascript - disable a textbox in another page PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.