php: preg_match failed with special character pattern - php

I have an issue with php regex. I have same regex in JS and it works. I don't know what is the problem.
this is the php code regex:
echo $password; // 9Gq!Q23Lne;<||.'/\
$reg_password = "/^[-_0-9a-záàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ0\d!##$%^&*()_\+\{\}:\"<>?\|\[\];\',\.\/\x5c~]{6,30}$/i";
if(isset($password) &&
(!preg_match($reg_password, $password) || !preg_match("#[a-z]#", $password) || !preg_match("#[\d]#", $password))
){
echo "you failed";
}
original password from html input:
9Gq!Q23Lne;<||.\'/\
it is the same value just before the $reg_password.
I have make a test using escape_string from mysqli method but it doesn't work too:
$password = $this->db->escape_string($password);
echo $password; // 9Gq!Q23Lne;<||.\'/\\
I don't know what is my problem because I have used regex101.com to test it and it works..
Any idea about that?
Thanks

In your pattern, you need to use single quote instead of double ;)
So it will be like this
$reg_password = '/^[-_0-9a-záàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ0\d!##$%^&*()_\+\{\}:\"<>?\|\[\];\',\.\/\x5c~]{6,30}$/i';

You don't need to call preg_match multiple times, just use lookahead to enforce your rules as in this regex:
^(?=.*?\d)(?=.*?[a-z])[-\wáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ0\d!##$%^&*()+{}:"<>?|\[\];',./\x5c~]{6,30}$
RegEx Demo
Code:
$re = "`^(?=.*?\\d)(?=.*?[a-z])[-\\wáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ0\\d!##$%^&*()+{}:\"<>?|\\[\\];',./\\x5c~]{6,30}$`mu";
$str = "9Gq!Q23Lne;<||.\'/\\";
if (!preg_match($re, $input)) {
echo "you failed";
}

Related

preg_match php with brackets and determined string is not working

Hi why is the preg_match with brackets and determined string is not working?
Pls let me know your solution to search for "uRole('Admin')".
<?php
$check ='if(uRole("Admin")||uRole("Design")){';
preg_match('/uRole("Admin")/i', $check)? echo 'match':"";
?>
Two reasons this isn't working...
You have to escape () in REGEX (otherwise it's assuming a group)
You don't use echo in a ternary operator; it has to come before
echo (STATEMENT_TO_EVALUATE = [TRUE | FALSE]) : TRUE_VALUE : FALSE_VALUE;
Working code
$check ='if(uRole("Admin")||uRole("Design")){';
echo preg_match('/uRole\("Admin"\)/i', $check, $matches) ? "match" : "";
That is because the ( and ) is a special character in regular expressions used to create groups.
Because it is a special character, you should use a backslash to escape it:
if (preg_match('/uRole\("Admin"\)/i', $check)) {
echo 'match';
}
By the way, in this situation a simple stripos is probably more appropriate:
if (stripos($check, 'uRole("Admin")') !== false) {
echo 'match';
}

PHP only Cyrillic in input without JavaScript

Is there a way to make only Cyrillic to be able to put in input/post? I did it with if(ctype_alnum($imeiprezime) == false) and it's working but I can't add spaces. I want to allow inputs like Ilija Popivanov and Илија Попиванов.
You should be able to use this:
$string1 = ' Ilija Popivanov Илија Попиванов';
if(!preg_match('/[^\p{Cyrillic}\p{L} ]/u',$string1))
{
echo 'pass';
}else{
echo 'fail';
}
Essentially, if there are any non-Cyrillic non-space, or non-letter characters, preg_match will return true.

PHP replace everything between two symbols with something else

I'm trying to replace the domain name of email addresses, between # and . with ***
For example:
$email1 = info#mytestdomain.com
$email2 = info#mytestdomain.net
Need to be become
$email1 = info#***.com
$email2 = info#***.net
I know I can use the PHP preg_replace function but I'm not sure what regex I need to use in my case. So my question is, which regex should I use in my case to replace everything between # and . with ***?
Thanks
You can use this assertion based regex.
$eml = preg_replace('/#\K[^.]+/', '***', $eml);
Live Demo
Live demo
$email1 = "info#mytestdomain.com";
echo preg_replace("/(.*#)([^\.]+)(\..*)/","$1***$3",$email1);
Output:
info#***.com
You could use a positive lookahead also.
$email1 = "info#mytestdomain.com";
echo preg_replace("/[^#]+(?=\.)/","***",$email1);
Pattern Explanation:
[^#]+(?=\.) Matches any character but not of # one or more times only if the characters are followed by a literal dot.

Preg match and Preg replace specific format

I need help with preg match/replace forma i really cant understand how its working and what each element doing.
So far I have this:
$username = preg_replace('/\s+/', '_', $_POST['uname']);
if(preg_match('/^[a-zA-Z0-9]{5,12}+$/u', $username))
{
$username = trim(strip_tags(ucfirst($purifier->purify(#$_POST["uname"]))));
}
else
{
$message['uname']='wrong username input';
}
And for utf8(hebrew language) i got this:
if(preg_match("/^[\p{Hebrew} a-zA-Z0-9]{2,10}+$/u", $_POST['fname']))
{
//
}
which is working perfect, but I don't want to allow Hebrew on username just English.
I tried to play with that in multiple combinations, I tried to change but no success, and I did research on StackOverflow and Google but can't make it like I want I don't understand.
I used a RegEx site to and tried to build but with no success.
So until now I got this :
User can put 5-12 letters/numbers no special characters.
What i want is :
Can enter between 5-12 letters/numbers no special charcaters - i
already have it.
Allow whitespaces
preg_match if no mixed language's like E.G: $username = שדגדשsdsd; <- not allowed mixed languages.
And preg_replace to:
Replace white spaces to nothing (remove white spaces) i have this but i dont know if it correct:
$username = preg_replace('/\s+/', '', $_POST['uname']);
Also, I am using UTF-8 language .
EDIT:
With help of hwnd , i make it to work like i want the latest code:
if(preg_match('/^[\p{Hebrew}]{2,10}|[a-zA-Z]{2,10}$/u', $_POST['fname']) && preg_match('/^[a-zA-Z]{2,10}|[\p{Hebrew}]{2,10}$/u', $_POST['fname']))
{
$message = 'valid';
}else{
$message = 'Invalid';
}
Solved,Thanks.
I'm sure if your allowing whitespace in the username, you can suffice with just a space character but to be safe use \s which matches whitespace (\n, \r, \t, \f, and " "), for that you can just add that inside of your character class []
if (preg_match('/^[a-zA-Z0-9\s]{5,12}+$/u', $username)) { ...
And you can leave your preg_replace() function as is...
Update: To match different characters, but not mixed you could try the following:
$user = 'hwדגדשרביd'; // "invalid"
$user = 'fooo'; // "valid"
$user = 'שדגדשרביב'; // "valid"
if (preg_match('/^[\p{Hebrew}]{2,10}|[a-zA-Z]{2,10}$/u', $user)) {
echo "valid";
} else {
echo "invalid";
}
Your preg_replace for removing whitespace from the username is fine.
To allow only English letters, digits and whitespace in the username, use this:
if (preg_match('/^[a-zA-Z0-9\s]{5,12}+$/u', $username)) {
# $username is OK
}
else {
# $username is not OK
}

Php preg_match error message

I want to match a string using REGEX which follows the syntax:
Text/number
So my preg_match() function is...
if(preg_match("/[^A-Za-z/0-9]$/ ", $folio))
$err[] = "Wrong value, it's should be lik: C/455";
But getting error message...
Try this:
$folio = "Text/15";
if(preg_match('~[a-z]/[\d]~i', $folio))
echo "match";
else
echo "no match";
You needed to escape / using \. Also numbers is a subset of text and you need to include it in your text part. You need one or more text/numeric characters, so a + is required.
It adds up to the following statement:
if(preg_match("/^[A-Za-z0-9]+\/[0-9]+$/", $folio))
You either need to escape / or use different char to surround regexp, for example:
if(preg_match("#[^A-Za-z/0-9]$# ", $folio))
if ( ! preg_match('/\b[a-z]+\/[0-9]+\b/i', $folio)) {
$err[] = "Wrong value, it's should be like this: C/455";
}

Categories