Member Avatar

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

Recommended Answers

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 …

Jump to Post

All 2 Replies

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;
Member Avatar

thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.