【问题标题】:How can I check whether the input string partailly matches any word in the given array in php?如何检查输入字符串是否部分匹配php中给定数组中的任何单词?
【发布时间】:2020-10-22 04:35:33
【问题描述】:

例如我的输入字符串是

$edition = Vol.123 or Edition 1920 or Volume 951 or Release A20 or Volume204 or Edition967

如何检查字符串中的单词是否与数组中的任何单词匹配。

$editionFormats = ['Vol','Volume','Edition','Release'];

基本上我需要检查输入是否有Vol或Volume或Edition或Release。

谁能提供一种检查模式的方法?

我尝试使用str_pos()preg_grep()preg_match()split()str_split() 我的想法是在第一次出现句号或空格或数字后拆分字符串, 但是没找到。

【问题讨论】:

    标签: php arrays regex string


    【解决方案1】:

    正则表达式的解决方案:

    $edition[] = 'Vol.123';
    $edition[] = 'Edition 1920';
    $edition[] = 'Volume 951';
    $edition[] = 'Release A20';
    $edition[] = 'Unknown data';
    $editionFormats = ['Vol','Volume','Edition','Release'];
    $pattern = implode('|', $editionFormats);
    
    foreach ($edition as $e) {
        if (preg_match('/' . $pattern. '/', $e)) {
            echo $e . ' matches' . PHP_EOL;
        } else {
            echo $e . ' NOT matches' . PHP_EOL;
        }
    }
    

    Fiddle.

    【讨论】:

    • 嗨@u_mulder 谢谢你的回答,我会试试并告诉你。
    【解决方案2】:

    假设您的输入是单个字符串(从问题中对我来说并不明显)

    一种非正则表达式的方法是查看传入字符串中的单词集与您感兴趣的单词集之间的交集:

    $edition = 'Vol.123 or Edition 1920 or Volume 951 or Release A20'
    $editionFormats = ['Vol','Volume','Edition','Release'];
    
    // Break $edition into single words on, on space character.
    $edition_words = explode(" ", $edition);
    
    $present = !empty(array_intersect($edition_words, $editionFormats));
    

    如果您的意思是 $edition 只是其中之一; 即

    $edition = 'Volume 951'
    

    这种方法仍然有效;请注意,空格字符的拆分仅在有空格时才有效,因此您的“Vol.123”不会匹配,除非您还包括“Vol.”。在你的 $editionFormats 中。

    【讨论】:

    • 嗨@Howard 感谢您的回答。我的输入是字符串。这是我尝试问题的方法之一,它不适用于 Edition123 或 Volume986 。这就是我试图在出现句点、空格或数字时拆分它的原因。有没有办法在出现点、空格或数字时爆炸?
    • explode 不需要一个以上的参数来爆炸,这在这种情况下是一种痛苦。您的另一种方法是遍历 $edition_words 并使用 strpos 测试以查看输入字符串中是否有任何内容,这样您就不必担心必须拆分标识符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    相关资源
    最近更新 更多