How To use preg_match for - , + , . values? - php

I use this preg_match condition for matching positive, negative and decimal values
/^[0-9,-\.]{1,50}$/
But when I enter --34.000 it does not show error, when I enter 34...9868 it does not show error,
what I want is that it must accept only positive, negative and decimal values.

Better if you use something like is_numeric() if yuo need to check if it's a number.
And your regex is totally broke because as now it can accept even only a string containing 50 dots

As yes123 stated, there are better ways to detect if a given input string is a numeric value. If you'd like to stick to regular expressions, the following might be OK for you:
/^-?[0-9]+(?:\.[0-9]+)?$/
Explanation:
match start of the string ( ^)
match a possible - character (-?); the ? means "not required"
match at least one number ([0-9]+)
possibly match the whole statement in the parentheses ((?:...)?); ?: means "do not capture the subpattern"
a point (\.); the . needs to be escaped due to its special function
at least one number ([0-9]+)
match end of the string ($)

You need to split up your regular expression so that it only accepts the characters in the right places. For example:
/^[+\-]?([0-9]+,)*[0-9]+(\.[0-9]+)?$/
To explain this expression:
[+\-]?: This checks for a + or - prefix to the number. It's completely optional, but can only be a + or -.
([0-9]+,)*: This allows an optional set of comma-delimited numbers. This is for the thousands, millions etc.
[0-9]+: This requires that the value contains at least some numbers
(\.[0-9]+)?: Finally, this allows an optional decimal point with trailing numbers.

try this regex ^-?\d*\.?\d+$
i suppose it however cannot be limited to 50 chars

Related

Regular Expression of a particular String in PHP

I have this few strings:
'user/1/myid_print'
'user/2/myid_print'
'user/3/myid_print'
'user/4/myid_print'
'user/5/myid_print'
The second part is the dynamic one which must contain only integers. What is it's regular expression?
Try this:
/user\/\d+\/myid_print/
the \d+ matches a number which contains at least one digit.
if it is a non-zero number, replace the \d+ with [1-9]\d*
It depends a bit on what language you're using, but one valid answer for Python is:
user/\d/myid_print
The / character is often used in describing regular expressions and sometimes needs \ before it to make it match part of the string, a valid answer might be:
user\/\d\/myid_print
These match the text "user/" and "/myid_print" literally, and \d matches the pattern "any digit 0-9". If you need to match the numbers 1,2,3,4,5 only, then use [1-5] instead of \d
Test it here: https://regex101.com/r/mS4xN4/1

Using preg_match to validate a string format

I have an html form with an input for a sales order number which should have the format of K1234/5678. It should always start with the letter K then 4 numbers, a / and followed by another set of 4 numbers.
I'm trying to validate the formatting using preg_match and I'm getting lost in the syntax of preg_match. From http://php.net/manual/en/function.preg-match.php I've gotten close. With the following code I'm able to verify that it contains at least 1 letter, some numbers and at least 1 non- alphanumeric value.
$so= $_POST['so'];
if (preg_match(""/^(?=.*[a-z]{1})(?=.*[0-9]{4})(?=.*[^a-z0-9]{1})/i", $so))
{
print $so;
}
What is the correct syntax to use for this? Is preg_match even the best way to do this?
Try this:
preg_match("#^K[0-9]{4}/[0-9]{4}$#i", $so)
Explanation:
The # characters are regular expression delimiters - they indicate the start/end of the pattern. The ^ and $ indicate the start and end of the string - this means that it will only match if your sales order number is the only thing in the string. The letter K means match that letter, [0-9]{4} means match a digit exactly 4 times. The i at the end means a case-insensitive match - the K will match either "K" or "k".
When developing regular expressions, I often use regular expression testers - these allow you to enter your data and try a bunch of different things to refine your regex. Google PHP regex tester to find a list of tools. Also, there's a very complete reference to regular expressions at http://www.regular-expressions.info/.

How to use OR in this regex to get 2 or 3 numbers before a specific character?

My question is how do I modify the following regex to get the numbers from this string 160bhp, BUT also the numbers from the 90bhp, string?
For now, it takes only the 3 numbers and ignores the 2. I am trying with | without luck.
preg_match_all('/(\d{3})bhp\b,/', $str2b, $bhps);
Am guessing you may want to generalise this to match one or more digits before the bhp (with no upper limit)? If that's the case, use this:
preg_match_all('/(\d+)bhp\b,/', $str2b, $bhps);
Taking this a bit further, would zero or more whitespace characters be allowed between, e.g. "200 bhp"? If so, use this:
preg_match_all('/(\d+)\s*bhp\b,/', $str2b, $bhps);
And finally, does it need to be case insensitive, e.g. to allow 300BHP? If so, put an i after the final slash:
preg_match_all('/(\d+)\s*bhp\b,/i', $str2b, $bhps);
You simply change the value between the brackets to be {2,3}.
preg_match_all('/(\d{2,3})bhp\b,/', $str2b, $bhps);
This basically provides a minimum/maximum number of the preceding character definition that is to be matched.
\d{3} is saying there needs to be exactly 3 digits. Changing the {3} to * should solve the problem and allow you to retrieve any number of consecutive digits before the bhp.
preg_match_all('/(\d*)bhp\b,/', $str2b, $bhps);
regexpal is an excellent online regex tester.
preg_match_all('/(\d{2,3})bhp\b,/', $str2b, $bhps);
There's an additional quantifier that allows you to specify how many times a token can be repeated. The syntax is {min,max}, where min is zero or a positive integer number indicating the minimum number of matches, and max is an integer equal to or greater than min indicating the maximum number of matches. If the comma is present but max is omitted, the maximum number of matches is infinite.
Source: http://www.regular-expressions.info/repeat.html
Bt if you want it to match also 1bhp and 160000bhp for example, use this instead:
preg_match_all('/(\d+)bhp\b,/', $str2b, $bhps);
Which will capture any number of digits on the left of bhp

Matching ugly extra abbreviations and numbers in titles with PHP regex

I have to create regex to match ugly abbreviations and numbers. These can be one of following "formats":
1) [any alphabet char length of 1 char][0-9]
2) [double][whitespace][2-3 length of any alphabet char]
I tried to match double:
preg_match("/^-?(?:\d+|\d*\.\d+)$/", $source, $matches);
But I coldn't get it to select following example: 1.1 AA My test title. What is wrong with my regex and how can I add those others to my regex too?
In your regex you say "start of string, followed by maybe a - followed by at least one digit or followed by 0 or more digits, followed by a dot and followed by at least one digit and followed by the end of string.
So you regex could match for example.. 4.5, -.1 etc. This is exactly what you tell it to do.
You test input string does not match since there are other characters present after the number 1.1 and even if it somehow magically matched your "double" matching regex is wrong.
For a double without scientific notation you usually use this regex :
[-+]?\b[0-9]+(\.[0-9]+)?\b
Now that we have this out of our way we need a whitespace \s and
[2-3 length of alphabet]
Now I have no idea what [2-3 length of alphabet] means but by combining the above you get a regex like this :
[-+]?\b[0-9]+(\.[0-9]+)?\b\s[2-3 length of alphabet]
You can also place anchors ^$ if you want the string to match entirely :
^[-+]?\b[0-9]+(\.[0-9]+)?\b\s[2-3 length of alphabet]$
Feel free to ask if you are stuck! :)
I see multiple issues with your regex:
You try to match the whole string (as a number) by the anchors: ^ at the beginning and $ at the end. If you don't want that, remove those.
The number group is non-catching. It will be checked for matches, but those won't be added to $matches. That's because of the ?: internal options you set in (?:...). Remove ?: to make that group catching.
You place the shorter digit-pattern before the longer one. If you swap the order, the regex engine will look for it first and on success prefer it over the shorter one.
Maybe this already solves your issue:
preg_match("/-?(\d*\.\d+|\d+)/", $source, $matches);
Demo

Phone number validation in PHP

I need to validate phone number in PHP. I have made following regex, but I also need to it to accept numbers starting with plus char, how can I do that?
^[0-9]$
The regex you provided in your question (^[0-9]$) will only match a one digit phone number.
At the very least you probably need to add the + modifier to allow one or more digits:
^[0-9]+$
To add an optional + at the beginning, you'll need to escape it since + is a special character in regular expressions:
^\+?[0-9]+$
And finally, \d is shorthand for [0-9] so you could shorten the expression to
^\+?\d+$
use this
/^(+\d)\s((\d{3})\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
Try this:
/^[\+]?([0-9]*)\s*\(?\s*([0-9]{3})?\s*\)?[\s\-\.]*([0-9]{3})[\s\-\.]*([0-9]{4})[a-zA-Z\s\,\.]*[x\#]*[a-zA-Z\.\s]*([\d]*)/
will match:
+1 ( 111)111-1111, #111
111-111-1111
(111)111-1111 x 1
111.111.1111x1
etc.

Categories