Home > Software design >  PHP: How to find a big word in a small one
PHP: How to find a big word in a small one

Time:12-20

I have user input like: $name = 'Alexxxx' Or $name = 'Aaaalex'

And I have list of names like: $names = 'Jack Harry Alex Oscar'

I need to know that user input contains name from a list, but user can input 'raw' name. How I can check it?

I've tried variants like this. But all of this find half input name in List. While I need the other way around

preg_match(
    '/(.*)' . $name . '(.*)/',
    $this->listOfNames,
);
str_contains(
    $this->listOfNames, strtolower(trim($name))
);
strstr($this->listOfNames, $name) !== false;

CodePudding user response:

I'm hoping that I've understood correctly, if not, please do correct me in comments!

My understanding is that you want to know whether a user-inputted string contains at least one of the names listed in a string (separated by a space). For example, search Alexxxx for Jack Harry Alex or Oscar which is of course true because Alexxxx contains Alex.

On the other hand, inputting Bruno would return false.

If I've understood correctly, the key would be to split the string of names using explode by the space as delimiter, then iterate through each item checking it against the inputted string.

<?php
$inputName = 'Alexxxx';
$names = 'Jack Harry Alex Oscar';

//Get an array of the names from $name. Result: ["Jack","Harry","Alex","Oscar"]
$listOfNames = explode(" ", $names);

// Initially we're going to filter our new array ($listOfNames) 
//   and pass in the $inputName using "use". 
// The filter callback merely checks for string position using strpos, 
//   case insensitivity requires stripos.
// This will return ["Alex"] is this example. 
// A simple count() > 0 logic check will give us a true/false outcome 
//   stored in $inputFoundInList. count() will be zero is not found.

$inputFoundInList = count(array_filter($listOfNames, function ($name) use ($inputName) {
    return strpos($inputName, $name) !== FALSE;
})) > 0;

// Result will be 1 (or true)
echo $inputFoundInList;

  • Related