[英]Get the word from sentence that match to an array 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
例如,如果情況是:帶雙s
waterproofss
返回將是waterproof
的
您可以使用正則表達式解決您的問題。 首先,您需要 map 將您的手機殼放在類似字符串的鍵waterprofs|waterproffs|waterproffss
上,並為這些手機殼設置Waterproof
值。 您的映射鍵將作為正則表達式中的模式工作。 preg_match將檢查字符串中的模式。 如果模式匹配,那么它將返回您在 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
希望您對如何使用正則表達式顯示所需的值有一個基本的了解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.