hi guys i was wondering how could i build e regExp that says:
"this string may contain 1-25 letters that are not these specific words:"root","bin","download","shutdown"
So I thought:
$dang_words="/(root)|(bin)|(shutdown)|(download)/";
$reg_exp="/^[a-z]{1,25}$/";
if(preg_match($reg_exp,$field) || !preg_match($dang_words,$field))
{
echo "your input it's okkk!";
}
else
echo "this is a bad word!!";
But it's not working
why?
thanks
Luca
$dangerous_words="/(root)|(bin)|(shutdown)|(download)/";
$reg_exp="/^[a-z]{1,25}$/";
if(preg_match($reg_exp,strtolower(trim($field))) && !preg_match($dangerous_words,strtolower(trim($field))))
{
echo "your input it's okkk!";
}
else
echo "this is a bad word!!";
You have your logical operators messed up.. Just changed from || to &&.
Close... Try this:
/^(?!.*(root|bin|shutdown|download))[a-z]{1,25}$/
It uses a forward assertion
So, it becomes:
if (preg_match('/^(?!.*(root|bin|shutdown|download))[a-z]{1,25}$/', $content)) {
echo "Your input is ok";
} else {
echo "there is a bad word/invalid content";
}
I think your issue lies with all the ( ). In some old code I created a while ago I used this:
$stopInjectionVerbs = "/(alter|begin|cast|convert|create|cursor|declare|delete|drop|end|exec|fetch|insert|kill|open|select|sys|table|update)/";
$errors = array();
if (preg_match($stopInjectionVerbs, $select)) {
$errors[] = "Can not use SQL injection Strings";
}
This all works correctly. Have a go without the brackets around each individual word.
Related
I have few url in my database, it goes like:
id url
1 http://test.com/embed-990.html
2. http://test2.com/embed-011.html
3. http://test3.com/embed-022.html
How I could make a simple php code if one of url doesn't exist in database, just to load another? I need to check these url by domain as well.
For example something like this:
if($data['url'] == "test.com") {
echo "my embed code number 1";
} elseif($data['url'] == "test2.com") {
echo "my another embed code";
}
You can parse the URL to get the host then compare it.
$dataurl = array('http://test.com/embed-990.html',
'http://test2.com/embed-011.html',
'http://test3.com/embed-022.html');
foreach($dataurl as $url) {
switch(parse_url($url, PHP_URL_HOST)) {
case 'test.com':
echo 'test domain';
break;
case 'test2.com':
echo 'test domain 2';
break;
default:
echo 'unknown';
break;
}
echo $url . PHP_EOL;
}
Demo: https://3v4l.org/nmukK
For the question Something like SQL “LIKE” you could use a regex in preg_match.
You can use substr_count
if (substr_count($data['url'], 'test.com') > 0) {
echo "my embed code number 1";
}
else if (substr_count($data['url'], 'test2.com') > 0) {
echo "my embed code number 2";
}
or strpos
if (strpos($data['url'],'test.com') !== false) {
echo "my embed code number 1";
}
else if (strpos($data['url'],'test2.com') !== false) {
echo "my embed code number 2";
}
or preg_match
if(preg_match('/test.com/',$data['url']))
{
echo "my embed code number 1";
}
else if(preg_match('/test2.com/',$data['url']))
{
echo "my embed code number 2";
}
You can use Regx
$domains = ['test.com', 'test1.com', 'test20.com'];
foreach( $domains as $domain ){
if(preg_match('/test([0-9]*)\.com/', $domain, $match)){
echo "my embed code number {$match[1]}\n";
}
}
Outputs:
my embed code number
my embed code number 1
my embed code number 20
you can test it here
http://sandbox.onlinephpfunctions.com/code/1d4ed1d7505a43b5a06b5ef6ef83468b20b47799
For the regx
test matches test literally
([0-9]*) - capture group, matches 0-9 none or more times
\. matches . literally
com matches com literally
One thing to note is that placing the * outside the capture group ([0-9])* will match and pass the if, but will not capture anything within the capture group. This makes sense, but its important to note because you'll get this message:
Notice: Undefined offset: 1 in [...][...] on line 6
for test.com.
If you want to match the number in embed- You can use one of these
'/test\.com\/embed-([0-9]{3})\.html/'
'/\/embed-([0-9]{3})\.html/'
'/\/embed-([0-9]{3})\./'
Depending how specific you want to be. You can play around with different Regx on this page.
https://regex101.com/r/snuqRc/1
Regular expressions are very powerful, they are meant for pattern matching, which is what you need.
Cheers.
please help me..i'm stuck in here..
What i actually want is to check the password from repeating single character or digit.
Requirement for repeating
aaaa = false,
abbb = false
abag = false
a33f = false
abcd1234 = true
there is only once for a character should have in password. If more than once repeated, error returns. So hard to explain.
this is my draft code.
1)first i need to check whether the global configuration for repeating character is allowed or not, if yes my password can have repeating char or digit otherwise it would't. After this, i need to check whether the global configuration for lowercase,uppercase or capitals allowed or not.
if($globalCOnf['repeat_pass']=="yes")//allowed
{
//do nothing
}
else //not allowed
{
//stuck here :(
if(preg_match('/(.)\1{1,}/',$user_input_pass)) //only check "aaaa" not "aba"
{
echo "change password";
}
else
{
if($globalCOnf['having_lower_upper_capital']=="yes")//allowed
{
//do nothing
}
else
{
// can't continue
}
}
}
You can use array_count_values for this (An alternate regex free solution)
<?php
$password = 'abcdfa';
if(max(array_count_values(str_split($password)))>1)
{
echo "Choose another password as words you can't have repeatable characters";
}
OUTPUT:
Choose another password as words you can't have repeatable characters
You get that output because a is repeated two times.
Answer for the question.
if($globalCOnf['repeat_pass']=="yes")//allowed
{
//do nothing
}
else //not allowed
{
if(max(array_count_values(str_split($user_pass)))>1)
{
echo "change your password now!!!";
}
else
{
if($globalCOnf['having_lower_upper_capital']=="yes")//allowed
{
//do nothing
}
else
{
if(preg_match('/[A-Z]/', $user_pass))
{
echo "Can't use uppercase";
}
}
}
}
100% working.. :)
Try something like this -
(\d+).*\1
If you get any match there is a repeated character.
Just allow zero or more characters between two duplicate characters. If there is a match, then the string failed to pass the validation.
Code: (Demo)
$passwords=['aaaa','abbb','abAg','a33f','abcd1234'];
foreach($passwords as $pass){
echo "$pass: ";
if(!preg_match('/([a-zA-Z\d]).*\1/',$pass)){
echo "valid\n";
}else{
echo "failed\n";
}
}
Output:
aaaa: failed
abbb: failed
abAg: valid
a33f: failed
abcd1234: valid
Or as one-line: echo preg_match('/([a-zA-Z\d]).*\1/',$pass)?'failed':'valid'
Using this type of pattern is much more direct that generating a temporary array of characters and counting their occurrences and checking the highest count.
I am currently trying to get my head around some basic php string functions. I currently use this code which determines if the username entered in long enough e.g.:
if (strlen($_GET['name']) < 3) {
echo 'First Name should be at least 3 characters long!';
exit;
}
And this works just fine. Which string function should I use though if I want to to check on a specific name? E.g. I would like to trigger a message once someone enters a specific Word in the form field.
Some expert advice would be greatly appreciated.
This link of 60 PHP validation functions is an excelent resource.
For your case as to check a name, you could use something like:
if (strtolower($_GET['name']) === 'joe') {
// Do something for Joe
}
elseif (in_array(strtolower($_GET['name']), array('dave', 'bob', 'jane')) {
// Do something else for Dave, Bob or Jane
}
The strtolower will ensure that upper, lower or mixed case names will match.
You don't need a function for that. You can use a if statement and ==:
if ( $_GET['name'] == 'Dave' )
{
// user entered 'Dave'
}
if statement, or if you plan to check against multiple names, switch().
switch($_GET['name']){
case "Eric":
//Eric
break;
case "Sally":
//Sally
break;
case "Tom":
//Tom
break;
default:
//Unknown
}
Its good practice to check that $_GET['name'] is set before using. To answer your question a good way IMO is in_array(needle,haystack)
<?php
if (!empty($_GET['name']) && strlen($_GET['name']) < 3) {
echo 'First Name should be at least 3 characters long!';
exit;
}
//From a database or preset
$names = array('Bob','Steve','Grant');
if(in_array($_GET['name'], $names)){
echo 'Name is already taken!';
exit;
}
?>
You can use strstr or stristr(case-insensitive) function, If want to search for specific word in a sentence.
Just check php mannual for strstr, and stristr.
I would like to "validate" my posted phone number. I don't really care about the format, i just want to use only numbers and some chars.
I tried this code, but if i type at least one number to my string then string will be valid. (for ex.: asdafadas-1asd will be valid)
How to fix this?
$phonebool=true;
if (!(strcspn($_POST['phone'], '0123456789-/ ') != strlen($_POST['phone']) )){
$_SESSION['phone_err']='Only numbers and -/';
$phonebool=false;
}
thank you.
You should use a regular expression instead, something like:
/^[0-9\/-]+$/
Otherwise have a look at libphonenumber - it seems that a php port exists: https://github.com/davideme/libphonenumber-for-PHP
Examples:
var_dump(preg_match('/^[0-9\/-]+$/', 'asdafadas-1asd'));
=> int(0)
var_dump(preg_match('/^[0-9\/-]+$/', '12/34-56'));
=> int(1)
Try This .
if(ereg("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", $number) ) {
echo "works";
} else {
$errmsg = 'Please enter your valid phone number';
}
Working code
if (!(preg_match("([0-9-]+)", $_POST['phone']) != strlen($_POST['phone']) )){
$_SESSION['phone_err']='Only numbers and -/';
$phonebool=false;
}
one recommendation: use javascript/jquery to validate your forms, so the users can correct right away before submit.
Try this:
$phonebool=true;
if (!(preg_match("([0-9-]+)", $_POST['phone']) != strlen($_POST['phone']) )){
$_SESSION['phone_err']='Only numbers and -/';
$phonebool=false;
}
I am trying to validate if a domain does have GET parameters with preg_match and and a REGEX, which i require it to have for my purposes.
What I have got working is validating a domain without GET parameters like so:
if (preg_match("/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}$/", 'domain.com')) {
echo 'true';
} else {
echo 'false';
}
I get true for this test.
So far so good. What I am having trouble with is adding in the GET parameters, Amongst a number of REGEX's I have tried with still no luck is the following:
if (preg_match("/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}([/?].*)?$/", 'domain.com?test=test')) {
echo 'true';
} else {
echo 'false';
}
Here i get false returned and hence am not able to validate a domain with GET parameters which are required.
Any assistance will be much appreciated ^^
Regards
This code is not tested, but I think it should work:
$pattern = "([a-z0-9-.]*)\.([a-z]{2,3})"; //Host
$pattern .= "(\?[a-z+&\$_.-][a-z0-9;:#&%=+\/\$_.-]*)?"; //Get requests
if (preg_match($pattern, 'domain.com?test=test')) {
echo 'true';
} else {
echo 'false';
}
What is the advantage of using a REGEX?
Why not just
<?php
$xGETS = count($_GET);
if(!$xGETS)
{
echo 'false';
} else {
echo 'true';
}
// PHP 5.2+
$xGETS = filter_var('http://domain.com?test=test', FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED);
if(!$xGETS)
{
echo 'false';
} else {
echo 'true';
}
Your first regular expression will reject some valid domain names (e.g. from the museum and travel TLDs and domain names that include upper case letters) and will recognize some invalid domain names (e.g. where a label or the whole domain name is too long).
If this is fine with you, you might just as well search for the first question mark and treat the prefix as domain name and the suffix as "GET parameters" (actually called query string).
If this is not fine with you, a simple regular expression will not suffice to validate domain names, because of the length constraints of domain names and labels.