Reputation: 21947
I want know, what regular expression should I have for my string. My string can contains only "|" and digits.
For example: "111|333|111|333". And string must begin from number. I am using this code, but he is ugly:
if (!preg_match('/\|d/', $ids)) {
$this->_redirect(ROOT_PATH . '/commission/payment/active');
}
Thank you in advance. Sorry for my english.
Upvotes: 2
Views: 196
Reputation: 44346
The regex is:
^\d[|\d]*$
^ - Start matching only from the beginning of the string
\d - Match a digit
[] - Define a class of possible matches. Match any of the following cases:
| - (inside a character class) Match the '|' character
\d - Match a digit
$ - End matching only from the beginning of the string
Note: Escaping the |
is not necessary in this situation.
Upvotes: 2
Reputation: 455312
Looking at your example I assume you are looking for a regex to match string that begin and end with numbers and numbers are separated with |
. If so you can use:
^\d+(?:\|\d+)*$
Explanation:
^ - Start anchor.
\d+ - One ore more digits, that is a number.
(? ) - Used for grouping.
\| - | is a regex meta char used for alternation,
to match a literal pipe, escape it.
* - Quantifier for zero or more.
$ - End anchor.
Upvotes: 3
Reputation: 8347
I think /^\d[\d\|]*$/
would work, however, if you always have three digits separated by bars, you need /^\d{3}(?:\|\d{3})*$/
.
EDIT:
Finally, if you always have sequences of one or more number separated by bars, this will do: /^\d+(?:\|\d+)*$/
.
Upvotes: 1
Reputation: 545913
A string that contains only |
or digits and begins with a digit is written as ^\d(\||\d)*$
. That means: either \|
(notice the escape!) or a digit, written as \d
, multiple times.
The ^
and $
mean: from start to end, i.e. there’s no other character before or after that.
Upvotes: 1