1

I want to use preg_match and regular expression in PHP to check that a string starts with either "+44" or "0", but how can I do this without the + being read as matching the preceding character once or more? Would (+44|0) work?

RJE95
  • 45
  • 4
  • 1
    Use a backslash to escape. `(\+44|0)` – PurkkaKoodari Apr 20 '14 at 13:11
  • 1
    Double backslash, actually. PHP itself doesn't know know regular expression semantics, so you have to pass it as a string, where the regular expression's backslash needs to be escaped again. – Wormbo Apr 20 '14 at 13:14
  • [**Related ...**](http://stackoverflow.com/questions/399078/what-special-characters-must-be-escaped-in-regular-expressions) – HamZa Apr 20 '14 at 13:23

3 Answers3

4

use the ^ to signify start with and a backslash \ to escape the + character. So you'll check for

^\+44 | ^0

In php, to store the regexp in a string, you don't need to double backslash \ to confuse things, just use single quotes instead like:

$regexp = '^\+44 | ^0';

In fact, you don't even need to use anything, this works too:

$regexp = "^\+44 | ^0";
Joshua Kissoon
  • 3,269
  • 6
  • 32
  • 58
  • 1
    As I will be adding more to the pattern, and am worried that it won't separate it unless there are brackets, I decided to go with the \\ method, but thank you for teaching me this too :) – RJE95 Apr 20 '14 at 13:28
3

The backslash is the default escape character for regular expressions. You may have to escape the backslash itself as well if it is used in a PHP string, so you'd use something like "(\\+44|0)" as string constant. The regular expression itself would then be (\+44|0).

Wormbo
  • 4,978
  • 2
  • 21
  • 41
2

You can do it several ways. Amongst those I know two:

One is escaping the + with escape character(i.e. back slash)

^(\+44|0)

Or placing the + inside the character class [] where it means the character as it's literal meaning.

^([+]44|0)

^ is the anchor character that means the start of the string/line based on your flag(modifier).

Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85