简体   繁体   English

从句子中获取与数组匹配的单词 PHP

[英]Get the word from sentence that match to an array PHP

Currently I have this variable in php目前我在php中有这个变量

   @if(count($label_types) > 0)
   @foreach ($label_types as $label_type)
      @if($label_type)
        {{ $label_type->fldLabelTypeName }}
      @endif
   @endforeach
   @endif

Which contains the following rows其中包含以下行

Waterproof (This is waterproof)

Glossy

Normal

Now since waterproof has the (This is waterproof) on the records现在因为waterproof has the (This is waterproof)

Now I want to only return the words that matches with these keywords现在我只想返回与这些关键字匹配的词

waterproof , glossy , normal waterproofglossynormal

whether they are uppercases , lowercasesuppercases还是lowercases

For example if the case is: waterproofss with double s例如,如果情况是:带双s waterproofss

the return would be waterproof返回将是waterproof

You can solve your problem by using regex.您可以使用正则表达式解决您的问题。 First, you need to map your cases on string-like key waterprofs|waterproffs|waterproffss and value Waterproof for these cases.首先,您需要 map 将您的手机壳放在类似字符串的键waterprofs|waterproffs|waterproffss上,并为这些手机壳设置Waterproof值。 Your mapped key will work as a pattern in a regex.您的映射键将作为正则表达式中的模式工作。 preg_match will check your pattern in your string. preg_match将检查字符串中的模式。 if the pattern matched, then it will return its value which one you defined in your map.如果模式匹配,那么它将返回您在 map 中定义的值。

function getLabel(string $string)
{
    // You own custom map using regex, key-value pair,
    $matchersMap = [
        'waterproofs|waterproof' => 'Waterproof',
        'glossies|glossy' => 'Glossy',
        'normal' => 'Normal'
    ];

    $result = -1;

    foreach($matchersMap as $matchesKey => $replaceValue) {
        if (preg_match("/$matchesKey/", strtolower($string))) {
            $result = $replaceValue;
            break;
        }
    }

    return $result;
}

var_dump(getLabel("waterproof has the (This is waterproof)")); //Waterproof 

Hopefully, you will get a minimum idea of how you will show your desired value by using regex.希望您对如何使用正则表达式显示所需的值有一个基本的了解。

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

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