1

I have a regex to match numbers that are formatted as a phone number or similar to phone numbers. I have to omit the numbers that are start with forward slashes, since that might be a part of a URL. I have used the following regex. It works well in all situations but any number without forward slash in initial point of sentence is ignored by the regex. can anyone help me to fin the mistake here?

/[^\/0-9](\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{2,3}[\s.-]?\d{3}/i

Test Case 1:

23242424 242424242 24242424424 2424244242 242 24242424/1212121212 1 05454545454 5454045454 0115545454 /454545454

Output 1: (Matches indicated in bold italic)

23242424 242424242 24242424424 2424244242 242 24242424/1212121212 1 05454545454 5454045454 0115545454 /454545454

Test Case 2: (a space in front of first number)

23242424 242424242 24242424424 2424244242 242 24242424/1212121212 1 05454545454 5454045454 0115545454 /454545454

Output 2: (Matches indicated in bold italic)

23242424 242424242 24242424424 2424244242 242 24242424/1212121212 1 05454545454 5454045454 0115545454 /454545454

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
Fasna
  • 494
  • 1
  • 10
  • 27

2 Answers2

2

You can use a negative lookbehind instead of a negated character class to also match start of string positions:

'/(?<![\/0-9])(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{2,3}[\s.-]?\d{3}/'
  ^^^^^^^^^^^^

See the regex demo

Here, (?<![\/0-9]) is a negative lookbehind that matches a location that is not immediately preceded with a forward slash or a digit.

Note you do not need the case insensitive modifier unless this is a part of a longer pattern where you also match letters.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
0

My way is quite brutal, but i would simply remove any numbers beginning with / from the main string before searching for numbers. Something like $str = preg_replace('/\/\d+/', '', $str);

MarvinLeRouge
  • 324
  • 1
  • 11