I need to check / replace a Phone number in a Form Field with regex and it should really be simple.
I can't find Solutions in this Format:
"place number"
so: "0521 123456789"
Nothing else should work. No special Characters, no country etc.
Just "0521 123456789"
Would be great if someone could provide a solution as I'm not an Expert with regex (and PHP).
You can use the following RegEx:
^0[1-9]\d{2}\s\d{9}$
That will match it how it is exactly
Live Demo on RegExr
How it works:
^ # String Starts with ...
0 # First Digit is 0
[1-9] # Second Digit is from 1 to 9 (i.e. NOT 0)
\d{2} # 2 More Digits
\s # Whitespace (use a [Space] character instead to only allow spaces, and not [Tab]s)
\d{9} # Digit 9 times exactly (123456789)
$ # ... String Ends with
PHP code:
$regex = '~\d{4}\h\d{9}~';
$str = '0521 123456789';
preg_match($regex, $str, $match);
See a demo on ideone.com.
To allow only this pattern (i.e. no others characters), you can anchor it to the beginning and end:
$regex = '~^\d{4}\h\d{9}$~';
Related
I am having one line I have to replace that below is the line
/myhome/ishere/where/are.you.ha
Here I have a live regex
preg_match('/(.+\/)[^.]+(.+\.ha)/', $input_line, $output_array);
it results me live this
/myhome/ishere/where/.you.ha
But I need a answer like this
/myhome/ishere/where/you.ha
Please anyone help me to remove this dot.
You could write the pattern as this, which will give you 2 capture groups that you can use:
(.+\/)[^.]+\.([^.]+\.ha)$
Explanation
(.+\/) Capture group 1, match 1+ chars and then the last /
[^.]+ Match 1+ non dots
\. Match a dot
([^.]+\.ha) Match non dots, then .ha
$ End of string
Regex demo | Php demo
If you use $1$2 in the replacement:
$pattern = "/(.+\/)[^.]+\.([^.]+\.ha)$/";
$s = "/myhome/ishere/where/are.you.ha";
echo preg_replace($pattern, "$1$2", $s);
Output
/myhome/ishere/where/you.ha
Or see a code an example using preg_match with 2 capture groups.
You can use
/^(.+\/)[^.]*\.(.*\.ha)$/
See the regex demo. Details:
^ - start of a string
(.+\/) - Group 1: any one or more chars other than line break chars as many as possible and then /
[^.]* - zero or more chars other than a .
\. - a . char
(.*\.ha) - Group 2: any zero or more chars other than line break chars as many as possible and then .ha
$ - end of a string
Although I got the answer I was mistaking to put +\. in between
(.+/)[^.]+\.(.+\.ha)
preg_replace('/(.+\/)[^.]+\.(.+\.ha)/', '$1$2', $input_lines);
This is how it works.
I'm still trying to get to grips with regex patterns and just after a little double-checking if someone wouldn't mind obliging!
I have a string which should either contain:
A 10 digit (numbers and letters) licence key, for example: 1234567890 OR
A 25 digit (numbers and letters) licence key, for example: ABCD1EFGH2IJKL3MNOP4QRST5 OR
A 29 digit licence number (25 numbers and letters, separated into 5 group by hyphens), for example: ABCD1-EFGH2-IJKL3-MNOP4-QRST51
I can match the first two fine, using ctype_alnum and strlen functions. However, for the last one I think I'll need to use regex and preg_match.
I had a go over at regex101.com and came up with the following:
preg_match('^([A-Za-z0-9]{5})+-+([A-Za-z0-9]{5})+-+([A-Za-z0-9]{5})+-([A-Za-z0-9]{5})+-+([A-Za-z0-9]{5})', $str);
Which seems to match what I'm looking for.
I want the string to only contain an exact match for a string beginning with the licence number, and contain nothing other than mixed upper/lower case letters and numbers in any order and hyphens between each group of 5 characters (so a total of 29 characters - I don't want any further matches). No white space, no other characters and nothing else before or after the 29 digit key.
Will the above work, without allowing any other combinations? Will it stop checking at 29 characters? I'm not sure if there is a simpler way to express this in regex?
Thanks for your time!
The main point is that you need to use both ^ (start of string) and $ (end of string) anchors. Also, when you use + after (...), you allow 1 or more repetitions of the whole subpattern inside the (...). So, you need to remove the +s and add the $ anchor. Also, you need regex delimiters for your regex to work in PHP preg_match. I prefer ~ so as not to escape /. Maybe it is not the case here, but this is a habit.
So, the regex can look like
'~^[A-Za-z0-9]{5}(?:-[A-Za-z0-9]{5}){4}$~'
See the regex demo
The (?:-[A-Za-z0-9]{5}){4} matches 4 occurrences of -[A-Za-z0-9]{5} subpattern. The (?:...) is a non-capturing group whose matched text does not get stored in any buffer (unlike the capturing group).
See the IDEONE demo:
$re = '~^[A-Za-z0-9]{5}(?:-[A-Za-z0-9]{5}){4}$~';
$str = "ABCD1-EFGH2-IJKL3-MNOP4-QRST5";
if (preg_match($re, $str, $matches)) {
echo "Matched!";
}
How about:
preg_match('/^([a-z0-9]{5})(?:-(?1)){4}$/i', $str);
Explanation:
/ : regex delimiter
^ : begining of string
( : begin group 1
[a-z0-9]{5} : exactly 5 alphanum.
) : end of group 1
(?: : begin NON capture group
- : a dash
(?1) : same as definition in group 1 (ie. [a-z0-9]{5})
){4} : this group must be repeated 4 times
$ : end of string
/i : regex delimiter with case insensitive modifier
I've researched a little, but I found nothing that relates exactly to what I need and whenever tried to create the expression it is always a little off from what I require.
I attempted something along the lines of [AZaz09]{3,8}\-[AZaz09]{3,8}.
I want the valid result to only allow text-text, where either or the text can be alphabetical or numeric however the only symbol allowed is - and that is in between the two texts.
Each text must be at least three characters long ({3,8}?), then separated by the -.
Therefore for it to be valid some examples could be:
Text-Text
Abc-123
123-Abc
A2C-def4gk
Invalid tests could be:
Ab-3
Abc!-ajr4
a-bc3-25aj
a?c-b%
You need to use anchors and use the - so the characters in the character class are read as a range, not the individual characters.
Try:
^[A-Za-z0-9]{3,8}-[A-Za-z0-9]{3,8}$
Demo: https://regex101.com/r/xH3oM8/1
You also could simplify it a but with the i modifier and the \d meta character.
(?i)^[a-z\d]{3,8}-[a-z\d]{3,8}$
If accented letters should be allowed, or any other letter that exists in the Unicode range (like Greek or Cyrillic letters), then use the u modifier (for UTF-8 support) and \pL to match Unicode letters (and \d for digits):
$string ="
Mañana-déjà
Text-Text
Abc-123
123-Abc
A2C-def4gk
Ab-3
Abc!-ajr4
a-bc3-25aj
a?c-b%";
$regex='/^[\pL\d]{3,}-[\pL\d]{3,}$/mu';
preg_match_all($regex, $string, $matches);
var_export($matches);
Output:
array (
0 =>
array (
0 => 'Mañana-déjà',
1 => 'Text-Text',
2 => 'Abc-123',
3 => '123-Abc',
4 => 'A2C-def4gk',
),
)
NB: the difference with \w is that [\pL\d] will not match an underscore.
You could come up with the following:
<?php
$string ="
Text-Text
Abc-123
123-Abc
A2C-def4gk
Ab-3
Abc!-ajr4
a-bc3-25aj
a?c-b%";
$regex='~
^\w{3,} # at last three word characters at the beginning of the line
- # a dash
\w{3,}$ # three word characters at the end of the line
~xm'; # multiline and freespacing mode (for this explanation)
# ~xmu for accented characters
preg_match_all($regex, $string, $matches);
print_r($matches);
?>
As #chris85 pointed out, \w will match an underscore as well. Trincot had a good comment (matching accented characters, that is). To achieve this, simply use the u modifier.
See a demo on regex101.com and a complete code on ideone.com.
You can use this regex
^\w{3,}-\w{3,}$
^ // start of the string
\w{3,} // match "a" to "z", "A" to "Z" and 0 to 9 and requires at least 3 characters
- // requires "-"
\w{3,} // same as above
$ // end of the string
Regex Demo
And a short one.
^([^\W_]{3,8})-(?1)$
[^\W_] can be used as short for alnum. It subtracts the underscore from \w
(?1) is a subroutine call to the pattern in first group
Demo at regex101
My vote for #chris85 which is most obvious and performant.
This one
^([\w]{3,8}-[\w]{3,8})$
https://regex101.com/r/uS8nB5/1
I need help to write a regular expression to match numbers which may be broken up into sections by spaces or dashes e.g:
606-606-606
606606606
123 456-789
However, matches should be rejected if all the digits of the number are identical (or if there are any other characters besides [0-9 -]):
111 111 111
111111111
123456789a
If spaces/dashes weren't allowed, the Regex would be simple:
/^(\d)(?!\1*$)\d*$/
But how would I allow dashes and spaces in the number?
EDIT
How would I allow also letters in the same regex (dashes and spaces shoud be still allowed) e.g:
aaaaa - it's not ok
aa-aaa-aaa-aaaaa - it's not OK
ababab - it's OK
ab-ab-ab - it's OK
This rule checks only numbers.
^(?!(?:(\d)\1+[ -]*)+$)\d[\d- ]+$
Desired results can be achieved by this Regular Expression:
^(?!(?:(\d)\1+[ -]*)+$)\d[\d- ]+$
Live demo
Explanations:
^ # Start of string
(?! # Negative Lookahead to check duplicate numbers
(?: # Non-capturing group
(\d) # Capture first digit
\1+ # More digits same as lately captured one
[ -]* # Any spaces and dashes between
)+ # One or more of what's captured up to now
$ # End of string
) # End of negative lookahead
\d # Start of match with a digit
[\d- ]+ # More than one digit/dash/space
$ # End of string
The theory behind this regex is to use a lookaround to check if string contains any duplicate numbers base on the first captured number. If we have no match in this lookaround, then match it.
Even if you can, i wonder if a regex is the right tool to solve this problem. Just imagine your fellow developers scratching their heads trying to understand your code, how much time do you grant them? Even worse, what if you need to alter the rules?
A small function with some comments could make them happy...
function checkNumberWithSpecialRequirements($number)
{
// ignore given set of characters
$cleanNumber = str_replace([' ', '-'], '', $number);
// handle empty string
if ($cleanNumber == '')
return false;
// check whether non-digit characters are inside
if (!ctype_digit($cleanNumber))
return false;
// check if a character differs from the first (not all equal)
for ($index = 1; $index < strlen($cleanNumber); $index++)
{
if ($cleanNumber[$index] != $cleanNumber[0])
return true;
}
return false;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php regex , extract phone number from text/html
I have following requirement. There is a phone number field.
Its length should be between 8 and 10
It can contain only _ and white spaces
First and last elements should be digits
_ and white spaces should be in between 2 digits
Can I write a regular expression to validate the above things using php?
Example for valid entry: 231_901 347
Example for invalid entry: _123 567, 345__123
Also if possible, can you please write down the preg_match expression.
Here is the code which I tried:
$subject = "_012_345 69";
$pattern = '/[\d]{1}.[\d\s_]{5,10}.[\d]{1}$/';
$matches = preg_match($pattern, $subject);
echo($matches);
It should return 0 but it returns 1.
^(?=.{8,10}$)\d+(?:[ _]\d+)*$
Explanation:
^ # Start of string
(?=.{8,10}$) # Assert length 8-10
\d+ # One or more digits
(?: # followed by
[ _] # one space or underscore
\d+ # one or more digits
)* # zero or more times.
$ # End of string
Use regex pattern
^(?=.{8,10}$)(?=\d)(?=.*\d$)(?:\d|(?<=\d)[\s_](?=\d))+$
Explanation >>
^
Start if line/string
(?=.{8,10}$)
String size is 8-10 characters
(?=\d)
First character is digit
(?=.*\d$)
Last character is digit
(?:\d|(?<=\d)[\s_](?=\d))+
Allowed characters are (a) digits or (b) whitespace or underscore between digits
$
End of line/string
This meets all your requirements as I understand them:
^(?:\d[ _]*){7,9}\d$
As for those false positives you're getting, you just left off the start anchor (^). But even with anchor added it matches things like
1_________2
and
01234567890123
I'm assuming those are invalid because you meant there have to be eight to ten digits, not that the overall length should be eight to ten.