简体   繁体   English

搜索单数和复数形式的针

[英]Search for needle in singular and plural variant

I am looking for a good solution to check, whether a word (even in the singular-version) is existing in a specific string. 我正在寻找一个好的解决方案来检查特定字符串中是否存在一个单词(即使是单数形式)。

Example: 例:

$search = 'users';

$array = [
    'index-users',
    'view-users',
    'create-users',
    'index-user-roles',
    'view-user-roles',
    'create-user-roles',
    'index-todos',
    'view-todos',
    'create-todos',
    'index-attributes',
    'view-attributes',
    'create-attributes',
];

I expect the result for the check for users to be true here. 我希望这里的users检查结果是true

Even in this example (Singular) the result should be true : 即使在此示例(单数)中,结果也应为true

<?php

$search = 'users';

$array = [
    'view-user-roles',
    'create-user-roles',
    'index-todos',
    'view-todos',
    'create-todos',
    'index-attributes',
    'view-attributes',
    'create-attributes',
];

I thought about using a regex, but my skills are not good enough to cover the plural and singular-variants. 我曾考虑过使用正则表达式,但是我的技能不足以覆盖复数形式和单数形式。

I tried 我试过了

\b(\w*users\w*)\b

but this does not cover the singular variant. 但这不包括单数形式。 I added a short example: https://www.regextester.com/?fam=110732 我添加了一个简短的示例: https : //www.regextester.com/?fam=110732

You can achieve something like this with preg_grep() 您可以使用preg_grep()实现类似的操作

$array = [
        'index-users',
        'view-users',
        'create-users',
        'index-user-roles',
        'view-user-roles',
        'create-user-roles',
        'index-todos',
        'view-todos',
        'create-todos',
        'index-attributes',
        'view-attributes',
        'create-attributes',
];

$search = 'use'; 

$result = preg_grep('~' . $search . '~', $array);
if (!empty($result)){
   var_dump($result);
} else {
  echo 'No match found';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM