user2264941
user2264941

Reputation: 407

How to convert regular expression from java to php

I have regular expression:

(9[0-5[7-9]]{1}[\d]{10})|([0-2]\d{11})

This expression work for java, but doesn't work for php. Help me to convert in to php

// true
System.out.println("123456789012".matches("(9[0-5[7-9]]{1}[\\d]{10})|([0-2]\\d{11})"));
System.out.println("973456789012".matches("(9[0-5[7-9]]{1}[\\d]{10})|([0-2]\\d{11})"));
System.out.println("000456789012".matches("(9[0-5[7-9]]{1}[\\d]{10})|([0-2]\\d{11})"));

// false
System.out.println("12345678901".matches("(9[0-5[7-9]]{1}[\\d]{10})|([0-2]\\d{11})"));
System.out.println("963456789012".matches("(9[0-5[7-9]]{1}[\\d]{10})|([0-2]\\d{11})"));

Upvotes: 0

Views: 229

Answers (2)

Jonny 5
Jonny 5

Reputation: 12389

Looks like it should only exclude 96... from the starting 9 ones, thus can be simplified to:

^(?:9(?!6)|[0-2])\d{11}$

For PHP need to wrap the pattern into delimiters.

Test at regex101

Upvotes: 1

nhahtdh
nhahtdh

Reputation: 56809

Your Java regex can be rewritten as:

9[0-57-9]\d{10}|[0-2]\d{11}

Since Java String.matches() makes sure the whole string matches the regex, you need to anchor the regex in PHP to get the same effect:

'~^(?:9[0-57-9]\d{10}|[0-2]\d{11})$~'

Upvotes: 0

Related Questions