首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从与数组PHP匹配的句子中获取单词

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

Stack Overflow用户
提问于 2020-05-28 07:06:13
回答 1查看 78关注 0票数 1

目前,我在php中有这个变量

代码语言:javascript
复制
   @if(count($label_types) > 0)
   @foreach ($label_types as $label_type)
      @if($label_type)
        {{ $label_type->fldLabelTypeName }}
      @endif
   @endforeach
   @endif

它包含以下行

Waterproof (This is waterproof)

Glossy

Normal

现在由于记录上的waterproof has the (This is waterproof)

现在我只想返回与这些关键字匹配的单词

waterproofglossynormal

无论是uppercases还是lowercases

例如,如果情况是:具有双swaterproofss

返回的结果是waterproof

EN

回答 1

Stack Overflow用户

发布于 2020-05-28 07:44:43

您可以通过使用regex来解决您的问题。首先,对于这些案例,您需要将案例映射到类似字符串的键waterprofs|waterproffs|waterproffss和值Waterproof上。您的映射键将作为正则表达式中的模式工作。preg_match将检查字符串中的模式。如果模式匹配,那么它将返回您在映射中定义的值。

代码语言:javascript
复制
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 

希望您能对如何使用正则表达式显示所需的值有一个最基本的了解。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62054310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档