PHP5, if, elseif, if with preg_replace not working - php

I tried to look on here as to why this code is not working, got no where and now I'm hoping someone can help me out.
function validateData($string) {
if (empty($string)) {
return 'error';
} elseif (strlen($string) <= 1) {
return 'error';
} elseif (preg_match('[a-zA-Z0-9]+\ ?', $string)) {
return 'error';
} else {
return 'normal';
}
}
When I execute the above code, using:
echo validateData('Test');
echo validateData('Test!');
These both echo 'normal'.. however, the second example contains the '!' in the string and should return 'error' because of the preg_match statement in the above code.
Achievement Objective. Check a string to make sure that it is not EMPTY, that it is longer than 1 character and only contains a-z, A-Z, 0-9 or a space. So no special characters.
Thank you very much in advance to all answers, I really appreciate it!
Ken

Your pattern should look like this:
preg_match('/([^a-zA-Z0-9 ])+/', $string);
The ^ symbol is used to negate a character set.

use !preg_match(pattern,$string), if you need to validate strings which contains spaces, then use following, otherwise, remove \s from preg_match pattern
function validateData($string) {
if (empty($string)) {
return 'error';
} elseif (strlen($string) <= 1) {
return 'error';
} elseif (!preg_match('/^[A-Za-z0-9\s]+$/', $string)) {
return 'error';
} else {
return 'normal';
}
}

If the string is empty, it will be equal to 0 when you ask for it's string length, therefore testing empty($string) is useless since it is covered by the second test.
Using a regex adds complexity without benefit here, there is a dedicated function to return true or false for alphanumeric string: ctype_alnum($string)
Your function can just be:
function validateData($string) {
return (strlen($string) <= 1 || !ctype_alnum($string)) ? 'error' : 'normal';
}

try:
preg_match('/[a-zA-Z0-9]+\ ?/', $string)

Replace
preg_match('[a-zA-Z0-9]+\ ?', $string)
with
preg_match('/[^a-zA-Z0-9]/', $string)

Related

how to detect some "$#%#*&$!" type characters from the String in php?

I have an Username input filed . if i want to detect some characters which is in an array like this $array = array('#','%','^') so Is there any built in function in php for that ? which will Take an Array and return true or false .
The easiest way would be:
if (str_replace($array, '', $username) != $username) {
do something;
}
You can write your own function of course:
function contains_unallowed($array = ['#', '%', '^']) {
return str_replace($array, '', $username) != $username;
}
It takes an array of characters as optional parameter and returns true or false. If it doesn't work, please replace the square braces [] with array().
array_intersect may help you - e.g.
$array = array('#','%','^');
if(array_intersect(str_split($username), $array)) {
echo "Found";
} else {
echo "Not Found";
}

How i can check with preg_match contain my string any digits or not?

I need to check in a string of digits, ie all other characters such as ~; & * ^ # & ^ Should not fall under check. I need it to form validation. Now i use that construction:
return ( ! preg_match("/^([0-9])+$/i", $str)) ? FALSE : TRUE;
I have a form for edeiting firstname and lastname of users. Also when someone try to add name with characters somth like that: "kickman!##$%^&())))(&^%$##$%" my form should complete validation without errors. But if i have there any digit i should get an error, somth like : "123kickman!##$%^&())))(&^%$##$%".
Try this:
if (!preg_match("#^[a-zA-Z0-9]+$#", $text)){
echo 'String also contains other characters.';
} else {
echo 'String only contains numbers and letters.';
}
or this:
function countDigits($str)
{
return preg_match_all( "/[0-9]/", $str );
}
If you are trying to see if all characters are digits, just create a function and pass the string to it:
$x = match("01234");
echo $x."<br>";
$x = match("0$#21234");
echo $x."<br>";
function match($str)
{
return ( ! preg_match("/^([0-9])+$/i", $str)) ? 0 : 1;
}
How about:
Edit according to question update:
if (preg_match('/\d/', $string)) {
echo "KO, at least one digit\n";
} else {
echo "OK, no digits found\n";
}
Or, in a function:
return !preg_match('/d/', $string);

PHP Function To Grab First Letter, Or Return # If It's a Number

I'm trying to write a php function that will grab the first letter from a long string ("ZT-FUL-ULT-10SF-S" would return "Z").
Some of the strings start with numbers, and for those, the function needs to return "#".
function returnFirst($rsrnum) {
substr("$rsrnum", 0, 1); {
echo "$rsrnum";
}
}
That's as far as I've gotten. How would I differentiate between numbers, and if it is a number, return #?
Thanks!
Edit: Seems to be working like a champ with:
function returnFirst($rsrnum) {
$char = substr($rsrnum, 0, 1);
return ctype_alpha($char) ? $char : "#";
}
Thanks!
Use ctype_alpha to check if the first character is a letter and return accordingly:
$char = substr($rsrnum, 0, 1);
return ctype_alpha($char) ? $char : "#";
A little delayed. but I think this might do the trick just fine!
function CheckFirst($String,$CharToCheck = 1){
if ($CharToCheck < 1){
return false;
}
$First_Char = $String{$CharToCheck - 1}; // Seek first Letter of Entered String
if (ctype_alpha($First_Char) === true){
// If the first Letter is in the aplhabet (A-Z/a-z)
return "First Character Is A String";
}elseif (ctype_digit($First_Char) === true){
// If The first Letter is a digit (0-9)
return "First Character Is A Digit";
}
}
I've left the function to return a string, so it's clear what will be returned upon pushing a string to the function. Suit the returns to your requirements
Edited the function to perform a better role within the script. It can now be called to check more than the first character of a string. Defaulting to the first

PHP : convert String to Float when possible

In PHP, I need to write a function that takes a string and returns its conversion to a float whenever possible, otherwise just returns the input string.
I thought this function would work. Obviously the comparison is wrong, but I don't understand why.
function toNumber ($input) {
$num = floatval($input); // Returns O for a string
if ($num == $input) { // Not the right comparison?
return $num;
} else {
return $input;
}
}
echo(gettype(toNumber("1"))); // double
echo(gettype(toNumber("3.14159"))); // double
echo(gettype(toNumber("Coco"))); // double (expected: string)
function toNumber($input) {
return is_numeric($input) ? (float)$input : $input;
}
try if($num){return $num;}else{return $input}, this will work fine, it will only jump to else statement part, when $num = 0
Well the fastest thing would be checking if $num == 0 rather than $num == $input, if I understand this correctly.

How to allow underscore and dash with ctype_alnum()?

How can I add the exception of _ and - as valid characters when using ctype_alnum() ?
I have the following code:
if ( ctype_alnum ($username) ) {
return TRUE;
} elseif (!ctype_alnum ($username)) {
$this->form_validation->set_message(
'_check_username',
'Invalid username! Alphanumerics only.'
);
return FALSE;
}
Since ctype_alnum only validates alpha numeric character,
Try this:
$sUser = 'my_username01';
$aValid = array('-', '_');
if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
echo 'Your username is not properly formatted.';
}
Use preg_match instead, maybe?
if(preg_match("/^[a-zA-Z0-9_\-]+$/", $username)) {
return true;
} else {
$this->form_validation->set_message('_check_username', 'Invalid username! Alphanumerics only.');
}
Here is how to use ctype_alnum AND have exceptions, in this case I also allow hyphens ( OR statement).
$oldString = $input_code;
$newString = '';
$strLen = mb_strlen($oldString);
for ($x = 0; $x < $strLen; $x++)
{
$singleChar = mb_substr($oldString, $x, 1);
if (ctype_alnum($singleChar) OR ($singleChar == '-'))
{
$newString = $newString . $singleChar;
}
}
$input_code = strtoupper($newString);
The regex equivalent is very brief and easy to read.
~^[\w-]+$~ This pattern requires the whole string to be comprised of one or more letters, numbers, underscores, or hyphens.
Regex allows you to skip the data preparation step and directly access the evaluation -- resulting in cleaner, leaner, more direct, professional-looking code.
if (preg_match('~^[\w-]+$~', $username)) {
return true;
} else {
$this->form_validation->set_message(
'_check_username',
'Invalid username! Alphanumerics, underscores, and hyphens only.'
);
return false;
}

Categories