0

I wanted to validate a string with preg_match but after a lot of struggle I just used if($str[0]!='x'....
but just out of curiosity I wonna know how to do this using preg_match
I'm getting a string as an input-
the 1st char in the string must be %
the 2nd char must be space
the 3rd char must be a number
and the rest can be anything (special chars/numbers/letters..)

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by arcticM
2

Something like this should work.

The / at the beginning and end of the pattern are delimiters.
The ^ denotes the start of the line or string.
The $ denotes the end of the line or string. Thus everything between the ^ and $ must match the expression, as opposed to just a portion.
The % is a literal character, so is only a percentage character.
The is another literal character, so is only a space character.
The \d matches a single digit between 0 and 9. If you want one or more digits, change it to \d+.
And the .+ matches any character appearing one or more times.

if(preg_match('/^% \d.+$/', $string)
    return true;
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.