收录日期:2020/10/28 06:55:42 时间:2010-09-07 02:23:31 标签:php

How can i check to see if a php string contains only 0-9 , and |? so it would accept 158,147|157,541|145,157 but not 125 ,148|126,4

Use regex:

if (!preg_match("~^[\d|,]+$~", $yourstr)) {
    // invalid

The regex explained:

  • ~ is just the regex delimiter

  • ^ is the start of string anchor

  • [...] is a character class

  • \d is a shorthand that means any character in the 0-9 range

  • | and , are just the | and , literals.

  • + is the "one or more" repetition operator

  • $ is the end of string anchor

It basically means:
Match a string that only has the following characters: 0-9, , and |.

Change it to:

if (!preg_match("~^[\d|,]*$~", $yourstr)) {
    // invalid

If you don't want it to reject the empty string. The * means "zero or more" (instead of +, which is "one or more")

Regex Reference: http://regular-expressions.info/