目前,我在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
例如,如果情况是:具有双s的waterproofss
返回的结果是waterproof
发布于 2020-05-28 07:44:43
您可以通过使用regex来解决您的问题。首先,对于这些案例,您需要将案例映射到类似字符串的键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 希望您能对如何使用正则表达式显示所需的值有一个最基本的了解。
https://stackoverflow.com/questions/62054310
复制相似问题