0

Am using code below to check presence of certain character via php and it works fine.

with code below, I can check if character a is presence in the variable and is working.

$mystring = 'my food is okay. its delicious';
$findme   = 'a';
$pos = strpos($mystring, $findme);
if ($pos !== false) {
echo 'data found';
}

Here is my issue: I need to check the also presence of multiple characters like m,e,s etc. any idea on how to achieve that.

jmarkatti
  • 621
  • 8
  • 29

3 Answers3

2

There are many ways to do this, from using multiple strpos to comparisons after a str_replace. Here we can split the string into an array and calculate the intersection with another array:

$mystring = 'my food is okay. its delicious';
$findme   = ['m', 'e', 's'];

Check for ANY of the characters in the array:

if(array_intersect($findme, str_split($mystring))) {
    echo "1 or more found";
}

Check for ALL of the characters in the array:

if(array_intersect($findme, str_split($mystring)) == $findme) {
    echo "all found";
}

And for fun, run the array through a callback and filter it based upon whether it is in the string. This will check for ANY:

if(array_filter($findme, function($v) use($mystring) {
                             return strpos($mystring, $v) !== false;
                         }))
{
    echo "1 or more found";
}

This will check for ALL:

if(array_filter($findme, function($v) use($mystring) {
                             return strpos($mystring, $v) !== false;
                         }) == $findme)
{
    echo "all found";
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
2

Another way to do this is with trim.

$mystring = 'my food is okay. its delicious';
$findme = 'ames';

$any = trim($findme, $mystring) != $findme;
$all = !trim($findme, $mystring);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

This function will do the trick for you:

/**
 * Takes an array of needles and searches a given string to return all
 * needles found in the string. The needles can be words, characters,
 * numbers etc.
 * 
 * @param array $needles
 * @param string $haystack
 * @return array|null
 */
function searchString(array $needles, string $haystack): ?array
{
    $itemsFound = [];
    foreach($needles as $needle) {
        if (strpos($haystack, $needle) !== false) {
            $itemsFound[] = $needle;   
        }
    }

    return $itemsFound;
}

https://3v4l.org/5oXGp

Lulceltech
  • 1,662
  • 11
  • 22