php - 从句子中获取与数组 PHP 匹配的单词
问题描述
目前我有这个变量php
@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)
记录在案
现在我只想返回与这些关键字匹配的单词
waterproof
, glossy
,normal
无论他们是uppercases
,lowercases
例如,如果情况是:waterproofss
双s
回报将是waterproof
解决方案
您可以使用正则表达式解决您的问题。首先,您需要将您的案例映射到这些案例的类似字符串的键waterprofs|waterproffs|waterproffss
和值Waterproof
上。您的映射键将用作正则表达式中的模式。preg_match将检查您的字符串中的模式。如果模式匹配,那么它将返回您在地图中定义的值。
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
希望您对如何使用正则表达式显示您想要的值有一个最低限度的了解。