[英]Find words from text file containing 2 specified letters using php
I have a list of words in a text file say: 我在文本文件中有一个单词列表,说:
Adam
Tony
Bob
Chris
Tommy
And I have 2 letters say t
& y
我有2个字母说t
& y
I need to find the words in the list containing both letters. 我需要在包含两个字母的列表中找到单词。 How can I do it? 我该怎么做?
Use file()
and preg_grep()
. 使用file()
和preg_grep()
。 file()
loads the words into an array, and preg_grep()
returns array entries that match the pattern. file()
将单词加载到数组中,并且preg_grep()
返回与模式匹配的数组条目。
$words = file('file.txt', FILE_IGNORE_NEW_LINES);
$letters = array('t','y');
$result = preg_grep('/[ty]/', $words);
Output: 输出:
Array
(
[1] => Tony
[4] => Tommy
)
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. 使用file()
将名称从文本文件中提取到数组中。 Next , you do a foreach
by cycling through the names one by one. 接下来,你做foreach
通过名字逐个循环。 Now you check whether t
or y
exists in the name and when found , you print the name of the person. 现在,您检查名称中是否存在t
或y
,并在找到时打印该人的姓名。
Using an array_map()
使用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. 如您所见,当我们搜索m
字母时, jimmy
和jammie
作为输出返回,它们出现了两次,因此我们将它们打印出来,而jacky
和monty
被忽略。
OUTPUT:
jimmy
jammie
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.