dongtuo4723 2018-11-26 17:25
浏览 88

从缺少字母的单词中查找txt列表中的单词

Searching how to do this from some days so far but without success. I've done a script to find words in a list containing some letters only once. It works.

Now i'd like to make a script to find words in a txt file list, with a word like this for example : W???EB??RD?. Positions of each letter are important. I just need to find words thats fit in. Missing letters are ?.

Could someone help me ?

Done this so far :

    $letters = "[A-Z]HITEBOARDS";
$array = explode("
", file_get_contents('test.txt'));

$fl_array = preg_grep("[A-Z]HITEBOARDS", $array);

echo $array[0];
echo $array[1];
echo $array[2];
echo $array[3];
var_dump($fl_array);
  • 写回答

1条回答 默认 最新

  • dongzice4895 2018-11-26 20:08
    关注

    As I mentioned in the comments your regex was missing the delimters

    $fl_array = preg_grep("[A-Z]HITEBOARDS", $array);
    

    Should be

    $fl_array = preg_grep("/[A-Z]HITEBOARDS/", $array);
    

    You may or should include the word boundary \b before and after a word, this will prevent matching partial words such as (for example) if you had this /\b[A-Z]here\b/ which could match therefore instead of just there. Without the boundaries matches could happen in the start, middle or end of partial words, which is probably not what you want. The boundary will match anything that is \W or in other words not \w or simpler [^a-z0-9_] or in English: matches anything not alpha, number or the underline, basically all your punctuation , special chars (except _ ) and whitespaces.

    So to put that in code would be this:

     $fl_array = preg_grep("/\b[A-Z]HITEBOARDS\b/", $array);
    

    Also instead of:

    $array = explode("
    ", file_get_contents('test.txt'));
    

    You can use

    $array = file('test.txt', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
    

    The file function is preferred because it breaks the file into an array based on the line endings (not dependent on OS vs as explode is). Besides that an better performance it also has two really useful flags. FILE_IGNORE_NEW_LINES is a given as this removes the line endings which are normally retained in the array by file(). The FILE_SKIP_EMPTY_LINES will do basically what it says and skip lines that are empty.

    Cheers.

    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序