Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does array element contain substring? [duplicate]

I'd like a function that checks whether an array's items contain a string. As such:

array(1 => 'Super-user', 'Root', 'Admin', 'Administrator', 'System', 'Website', 'Owner', 'Manager', 'Founder');

And then checking for admin12 should return true as a part of admin12 (admin) is also a part of the array.

I came this far:

$forbiddennames= array(1 => 'Super-user', 'Root', 'Admin', 'Administrator', 'System', 'Website', 'Owner', 'Manager', 'Founder');    

if(in_array( strtolower($stringtocheck), array_map('strtolower', $forbiddennames))){
        echo '"This is a forbidden username."';
    } else {
        echo 'true';
    }
}

Only this only echos "This is a forbidden username." when I check for admin. I want it also to echo when checking for admin12.

Is this possible (and how)?

like image 900
Isaiah Avatar asked Oct 27 '13 13:10

Isaiah


People also ask

How do I check if an array contains duplicates?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

Can an array contains duplicate elements?

We know that HashSet doesn't allow duplicate values in it. We can make use of this property to check for duplicates in an array. The idea is to insert all array elements into a HashSet . Now the array contains a duplicate if the array's length is not equal to the set's size.

How do you prevent duplicates in an array?

To prevent adding duplicates to an array:Use the indexOf() method to check that the value is not present in the array. The indexOf method returns -1 if the value is not contained in the array. If the condition is met, push the value to the array.


2 Answers

Loop through the $forbiddennames array and use stripos to check if the given input string matches any of the items in the array:

function is_forbidden($forbiddennames, $stringtocheck) 
{
    foreach ($forbiddennames as $name) {
        if (stripos($stringtocheck, $name) !== FALSE) {
            return true;
        }
    }
}

And use it like below:

if(is_forbidden($forbiddennames, $stringtocheck)) {
    echo "This is a forbidden username.";
} else {
    echo "True";
}

Demo!

like image 57
Amal Murali Avatar answered Sep 27 '22 21:09

Amal Murali


foreach ($forbiddennames as $forbiddenname) {
    $nametocheck = strtolower($stringtocheck);
    if(strpos($stringtocheck, $forbiddenname) !== false) {
        echo "This is a forbidden username.";
        break;
    }
}
like image 27
Ash Avatar answered Sep 27 '22 23:09

Ash