customizing preg_match - php

How do i preg_match an string to match the following format in php:
$m="123/456789/01";
if(pregmatch(????, $m){
// match
}else{
// doesn't match
}
i.e. 3 digits + "/" + 6 digits + "/" + 2 digits.

This is my try :)
if(preg_match('/[0-9]{3}\/[0-9]{6}\/[0-9]{2}/', $m)
{
// match
}
else
{
// Doesn't match
}

if (preg_match("#\d{3}/\d{6}/\d{2}#", $string)) {
// yeah
} else {
// nope
}
have a look at Pattern Syntax specifically Escape sequences.

Depending on what you would like to parse, regular expressions are not always needed:
$m="123/456789/01";
if(3 == count(sscanf($m, '%d/%d/%d'))) {
// match
}else{
// doesn't match
}

Related

How I can count char in a string and validate using PHP

I want to validate a string in such a way that in must have 2 hypens(-)
Strings input : (for eg)
B405Q-0123-0600
B405Q-0123-0612
R450Y-6693-11H0
R450Y-6693-11H1
Make use of substr_count function like this
<?php
echo substr_count( "B405Q-0123-0600", "-" )."\n";
echo substr_count( "B405Q01230600", "-" )."\n";
?>
Will Result
2
0
Validate like this
if(substr_count( $some_string, "-" ) == 2)
{
echo 'true';
// do something here
}else
{
echo 'false validation failed';
// some error handling
}
If your strings are like shown, then you can do
$re = "/(\\w{5}-\\w{4}-\\w{4})/";
$str = "B405Q-0123-0600"; // Your strings
if (preg_match($re, $str, $matches)) {
// valid
} else {
// invalid
}
I just need to check if the string is having two hyphens
If you only want to check if there are two hyphens anywhere, then you can split your strings on hyphens. If there are two and only two hyphens, then there will be 3 split parts.
$str = "B405Q-0123-0600"; // your strings
if (count(split("-", $str)) === 3) {
// two hyphens present
} else {
// not enough hyphens
}
Try this:
var str = "B405Q-0123-0612";
var arr = str.split("-");
if(arr.length=3){
alert("Your string contain 2 hyphens");
}
preg_match_all("/\-/",'B405Q-0123-0600',$match);
if(count($match[0]) == 2){
// valid
}else{
// invalid
}
use the below code
$string = "B405Q-0123-0612";
$arr = explode("-",$string)
if (count($arr) == 2)
{
//yes you have 2 hyphens
}
The above procedure is the simplest way to do
For checking this type of validation you are required to use the Regex of javascript. Use below given regular expression.
var check="^\w+([\s\-]\w+){0,2}$";
Now all need is to check this with creating the javascript function and you are half the way there.

What will be regex for checking alphanumeric dot dash and underschore using preg_match?

I am checking username entered by user
I'm trying to validate usernames in PHP using preg_match() but I can't seem to get it working the way I want it. I require preg_match() to:
accept only letters , numbers and . - _
i.e. alphanumeric dot dash and underscore only, i tried regex from htaccess which is like this
([A-Za-z0-9.-_]+)
like this way but it doesnt seem to work, it giving false for simple alpha username.
$text = 'username';
if (preg_match('/^[A-Za-z0-9.-_]$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
How can i make it work ?
i am going to use it in function like this
//check if username is valid
function isValidUsername($str) {
return preg_match('/[^A-Za-z0-9.-_]/', $str);
}
i tried answwer in preg_match() and username but still something is wrong in the regex.
update
I am using code given by xdazz inside function like this.
//check if username is valid
function isValidUsername($str) {
if (preg_match('/^[A-Za-z0-9._-]+$/' , $str)) {
return true;
} else {
return false;
}
}
and checking it like
$text = 'username._-546_546AAA';
if (isValidUsername($text) === true) {
echo 'good';
}
else{
echo 'bad';
}
You missed the +(+ for one or more, * for zero or more), or your regex only matches a string with one char.
if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
hyphen - has special meaning inside [...] that is used for range.
It should be in the beginning or in the last or escape it like ([A-Za-z0-9._-]+) otherwise it will match all the character that is in between . and _ in ASCII character set.
Read similar post Including a hyphen in a regex character bracket?
Better use \w that matches [A-Za-z0-9_]. In shorter form use [\w.-]+
What is the meaning for your last regex pattern?
Here [^..] is used for negation character set. If you uses it outside the ^[...] then it represents the start of the line/string.
[^A-Za-z0-9.-_] any character except:
'A' to 'Z',
'a' to 'z',
'0' to '9',
'.' to '_'
Just put - at the last in character class and add + after the char class to match one or more characters.
$text = 'username';
if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
function should be like this
function isValidUsername($str) {
return preg_match("/^[A-Za-z0-9._-]+$/", $str);
}

Regex PHP preg_match priority

I have this code
if (preg_match('/J[a-zA-Z0-9]+S/', $id)) {
echo "1";
}
else if (preg_match('/BUT[a-zA-Z0-9]+TN/', $id)) {
echo "2";
}
I have the id as BUTEqHLHxJSRr9DJZSMTN, Instead of getting 2 as output, I am getting 1.
This is has BUTEqHLHxJSRr9DJZSMTN which is making it match with the first expression. But this exp also has BUT/TN and it should also match with that regex also right?
Is there any way I can make the regex pattern in such a way that it do not check for matches from the middle of an expression, but rather it should match the beginning and end.
I don't know whether this is a stupid question to ask,but is there anyway its possible to prevent pregmatch to match from the begining?
You can use the ^ (beginning of string), $ (end of string) anchors to match an entire string.
For example, this will give you the result of 2 seeing how it matches the entire string from start to end.
$id = 'BUTEqHLHxJSRr9DJZSMTN';
if (preg_match('/^J[a-zA-Z0-9]+S$/', $id)) { echo "1"; }
else if(preg_match('/^BUT[a-zA-Z0-9]+TN$/', $id)) { echo "2"; }
Use word boundaries to avoid matching unwanted text:
if(preg_match('/\bJ[a-zA-Z0-9]+S\b/', $id)) {
echo "1";
}
else if(preg_match('/\bBUT[a-zA-Z0-9]+TN\b/', $id)) {
echo "2";
}
try ^ then it will check must be start from given string
if(preg_match('/^J[a-zA-Z0-9]+S/', $id)) {
echo "1";
}
else if(preg_match('/^BUT[a-zA-Z0-9]+TN/', $id)) {
echo "2";
}

PHP regular expression allowing at most 1 '.' or '_' character in string, and '.' or '_' can't be at beginning or end of string

I am writing a PHP validation for a user registration form. I have a function set up to validate a username which uses perl-compatible regular expressions. How can I edit it so that one of the requirements of the regular expression are AT MOST a single . or _ character, but NOT allow that character at the beginning or end of the string? So for example, things like "abc.d", "nicholas_smith", and "20z.e" would be valid, but things like "abcd.", "a_b.C", and "_nicholassmith" would all be invalid.
This is what I currently have but it does not add in the requirements about . and _ characters.
function isUsernameValid()
{
if(preg_match("/^[A-Za-z0-9_\.]*(?=.{5,20}).*$/", $this->username))
{
return true; //Username is valid format
}
return false;
}
Thank you for any help you may bring.
if (preg_match("/^[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+$/", $this->username)) {
// there is at most one . or _, and it's not at the beginning or end
}
You can combine this with the string length check:
function isUsernameValid() {
$length = strlen($this->username);
if (5 <= $length && $length <= 20
&& preg_match("/^[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+$/", $this->username)) {
return true;
}
return false;
}
You could probably do the whole lot using just one regex, but it would be much harder to read.
You can use the following pattern, I have divided it into multiple lines to make it more understandable:
$pattern = "";
$pattern.= "%"; // Start pattern
$pattern.= "[a-z0-9]+"; // Some alphanumeric chars, at least one.
$pattern.= "[\\._]"; // Contains exactly either one "_" or one "."
$pattern.= "[a-z0-9]+"; // Some alphanumeric chars, at least one.
$pattern.= "%i"; // End pattern, optionally case-insensetive
And then you can use this pattern in your function/method:
function isUsernameValid() {
// $pattern is defined here
return preg_match($pattern, $this->username) > 0;
}
Here is a commented, tested regex which enforces the additional (unspecified but implied) length requirement of from 5 to 20 chars max:
function isUsernameValid($username) {
if (preg_match('/ # Validate User Registration.
^ # Anchor to start of string.
(?=[a-z0-9]+(?:[._][a-z0-9]+)?\z) # One inner dot or underscore max.
[a-z0-9._]{5,20} # Match from 5 to 20 valid chars.
\z # Anchor to end of string.
/ix', $username)) {
return true;
}
return false;
}
Note: No need to escape the dot inside the character class.

help with validate field

how do i check a field contain number and alphabet.
something like $str = 3ab, ab3, a3
To check if a string contains number and alphabet you can do, write a small regex based function as:
function contains_num_alpha($str) {
return preg_match('/^[a-z0-9]+$/i',$str);
}
The regex used: ^[a-z0-9]+$
^, $ - anchors
[a-z0-9] - char class that matches a
single digit or a single alphabet.
[a-z0-9]+ - one or more
digits/alphabets.
i - to make the matching case
insensitive.
If you want to allow even empty string, you can change + to * in the regex.
You can use regex
$stringGood = 'abc2';
$stringBad = '2#2(7X%';
function isValidAlphaNum($str) {
return preg_match('/^[a-z\d]+$/i', $str);
}
var_dump(validateAlphaNum($stringGood)); // true
var_dump(validateAlphaNum($stringBad)); // false
If you wanted to allow uppercase and lowercase alphabetical characters, numbers and underscore you can use this regex: /^\w+$/
Not sure of what you're asking, but if you want to check whether a string has at least 1 alpha and 1 numeric character in it, then this regular expression ought to do it:
<?php
if (preg_match("^[a-zA-Z0-9]{1,}$", $str) {
// match was found;
}
?>
<?php
if (is_string("23")) {
echo "is string\n";
} else {
echo "is not an string\n";
}
var_dump(is_string('abc'));
var_dump(is_string("23"));
var_dump(is_string(23.5));
var_dump(is_string(true));
?>
Use the is_string function.
Returns TRUE if the argument type is string , FALSE otherwise.
<?php
$tests = Array(
"42",
1337,
"1e4",
"not numeric",
Array(),
9.1
);
foreach($tests as $element)
{
if(is_numeric($element))
{
echo "'{$element}' is numeric", PHP_EOL;
}
else
{
echo "'{$element}' is NOT numeric", PHP_EOL;
}
}
?>
If you want to check the input is numeric use the "is_numeric" function
It return true, if the argument is numeric. Else it return false

Categories