Domanda

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?

È stato utile?

Soluzione 3

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).

Altri suggerimenti

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";

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).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top