Fueling Your Coding Mojo

Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...

Popular Searches:
64
Q:

Regular expression for positive numbers from 1-99 up to 1 decimal places PHP

Hello everyone,

I hope you're all doing well. I have a question about regular expressions in PHP.

I am currently working on a project where I need to validate input for positive numbers ranging from 1 to 99, up to 1 decimal place.

For example, valid inputs would be: 1, 2, 3.5, 99.9
Invalid inputs would be: 0, -1, 100, 1.23

I was wondering if anyone could help me with the regular expression pattern to achieve this validation in PHP. I have been struggling with this for a while now and would greatly appreciate any guidance or suggestions.

Thank you in advance for your help!

All Replies

snikolaus

Hey folks,

I stumbled upon this thread and thought I could provide an alternative perspective. In my experience, I've dealt with similar validation requirements in PHP projects.

For the given scenario, you can use the following regular expression pattern:

/^(?:[1-9]|[1-9][0-9])\.?\d?$/

Here's how it works:

^ - Denotes the start of the string
(?:[1-9]|[1-9][0-9]) - Includes positive numbers ranging from 1 to 99
\.? - Matches an optional decimal point
\d? - Matches up to one digit after the decimal point
$ - Indicates the end of the string

This pattern will successfully validate inputs like 1, 3.5, and 99.9, while rejecting inputs like 0, -1, 100, and 1.23.

I hope this suggestion helps! If you have any further queries or need clarification, feel free to ask. I'll be glad to assist you.

azulauf

Hey there,

I've encountered a similar situation before where I needed to validate positive numbers within a specific range and decimal places. To achieve this, I used the following regular expression pattern in PHP:

/^(?:[1-9]|[1-9][0-9])(?:\.[0-9])?$/

Let me break down the pattern for you:

^ - Matches the start of the string
(?:[1-9]|[1-9][0-9]) - Matches a number from 1 to 99
(?:\.[0-9])? - Matches an optional decimal place and a single digit after it
$ - Matches the end of the string

This pattern will match inputs like 1, 2.5, 99.9, and so on, while rejecting inputs like 0, -1, 100, and 1.23.

I hope this helps! Let me know if you have any further questions or if there's anything else I can assist you with.

New to LearnPHP.org Community?

Join the community