Reputation: 345
I have a list of words in a text file say:
Adam
Tony
Bob
Chris
Tommy
And I have 2 letters say t
& y
I need to find the words in the list containing both letters. How can I do it?
Upvotes: 0
Views: 450
Reputation: 68476
You can do this way..
<?php
$arr = file('names.txt');
foreach($arr as $v)
{
if(strpos($v,'t')!==false && strpos($v,'y')!==false)
{
echo $v;
}
}
Using file()
the names are grabbed from the textfile into an array. Next , you do a foreach
by cycling through the names one by one. Now you check whether t
or y
exists in the name and when found , you print the name of the person.
Using an array_map()
array_map(function ($v){ echo (stripos($v,'t')!==false && stripos($v,'y')!==false) ? $v :'';},file('new.txt'));
EDIT :
what about when there are 2 letters that are the same though and I want the words that contain that letter twice..??
<?php
$names=array('jimmy','jacky','monty','jammie');
$v='m'; //<-- Lets's search for twice of m occurence
foreach($names as $v1)
{
$arr=array_count_values(str_split($v1));
if($arr[$v]==2)
{
echo $v1."\n";
}
}
As you can see jimmy
and jammie
are returned as output as we are searching for the m
letter and they have twice of the occurrence and thus we print them up , whereas jacky
and monty
are ignored.
OUTPUT:
jimmy
jammie
Upvotes: 1
Reputation: 76646
Use file()
and preg_grep()
. file()
loads the words into an array, and preg_grep()
returns array entries that match the pattern.
$words = file('file.txt', FILE_IGNORE_NEW_LINES);
$letters = array('t','y');
$result = preg_grep('/[ty]/', $words);
Output:
Array
(
[1] => Tony
[4] => Tommy
)
Upvotes: 3