[英]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
waterproof
, glossy
, normal
whether they are uppercases
, lowercases
是uppercases
还是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.