Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP: How to find a big word in a small one

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading