Php 如何使用strpos来匹配大多数单词?

Php 如何使用strpos来匹配大多数单词?,php,Php,我试图回显每个阵列键的测量单位名称 问题是,有时有些键值有缩写,正如我在haystack变量的最后一个键值中所示 $haystack = array( '15.1 ounces white chocolate', '1 ounce olive oil', '½ cup whipping cream', '1 tablespoon shredded coconut', '1 tablespoon lemon', '1 oz water' ); $n

我试图回显每个阵列键的测量单位名称

问题是,有时有些键值有缩写,正如我在haystack变量的最后一个键值中所示

$haystack = array(
    '15.1 ounces white chocolate',
    '1 ounce olive oil',
    '½ cup whipping cream',
    '1 tablespoon shredded coconut',
    '1 tablespoon lemon',
    '1 oz water'
);

$needles = 
    array(
        '0' => array(
            'id' => '1',
            'name' => 'cup',
            'abbreviation' => 'c'
        ), 
        '1' => array(
            'id' => '2',
            'name' => 'ounce',
            'abbreviation' => 'oz'
        ), 
        '2' => array(
            'id' => '3',
            'name' => 'teaspoon',
            'abbreviation' => 'tsp'
        ), 
        '3' => array(
            'id' => '4',
            'name' => 'tablespoon',
            'abbreviation' => 'tbsp'
    )
);

foreach($haystack as $hay){
    foreach($needles as $needle){
        if(strpos($hay, $needle['name']) !== false || strpos($hay, $needle['abbreviation']) !== false){
            $names[] = $needle['id'];
        }
    }
}
上面的代码返回以下结果():

我试图实现的是让它返回以下结果():


但是为了让它在“工作”代码中返回结果,我必须在缩写字符前加上1,这样strpo就不会与那些不正确的字符匹配。

缩写“c”表示“cup”太多了。你需要检查它是否是一个完整的单词。您可以通过在空格中嵌入搜索字符串来实现这一点,因此查找
“c”
,而不是
“c”
,或者使用正则表达式并匹配单词边界

请注意,如果你改变了这一点,你也必须在针头上加上“盎司”、“杯子”和“汤匙”(复数形式),否则你将无法找到它们。实际上,我不会写缩写,而是为每个单元保留一个“变体”数组,这样你会得到如下结果:

$needles = 
    array(
        '0' => array(
            'id' => '1',
            'name' => 'cup',
            'variations' => array('cups', 'cup', 'cp', 'c')
        ), 
    ...

然后,您可以搜索每个针的每个变化。

我同意这将是最好的方法,目前您的“c”太模糊,无法匹配。(这就是为什么你会得到巧克力、奶油和椰子的匹配)。我最终将每个单元的序列化变体存储到数据库中,就像你的例子一样,这比在字符串之间嵌入空格要有效得多。谢谢你。
Array
(
    [0] => 2
    [1] => 2
    [2] => 1
    [3] => 4
    [4] => 4
    [5] => 2
)
$needles = 
    array(
        '0' => array(
            'id' => '1',
            'name' => 'cup',
            'variations' => array('cups', 'cup', 'cp', 'c')
        ), 
    ...