PHP - 如何检查字符串中的匹配词?
PHP - how to check matched words from a string?
如何搭配?预期的有效输入:
email-sms-call
或
sms,email,call
或
sms email call
或
smsemailcall
只有在
之间有 space 时才会匹配
<?php
function contains($needles, $haystack) {
return count(
array_intersect(
$needles,
explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $haystack))
)
);
}
$database_column_value = 'email,sms,call';
$find_array = array('sms', 'email');
$found_array_times = contains($find_array, $database_column_value);
if($found_array_times) {
echo "Found times: {$found_array_times}";
}
else {
echo "not found";
}
?>
function contains_word($word, $text)
{
return null!==strpos($word,$text);
}
function count_keyWords($keyWords, $input) {
$numKeyWords=0;
foreach ($keyWords as $word) {
if(contains_word($word, $input)) {
$numKeyWords++;
}
}
return $numKeyWords;
}
//Usage
$input="sms,email,call";
$keyWords=['sms', 'email', 'call'];
$numKeywords=count_keyWords($keyWords, $input);
echo $numKeywords." found";
具有preg_split
功能:
function contains($needles, $haystack) {
if (!$needles || !$haystack)
return false;
$result = array_intersect($needles, preg_split("/[^A-Za-z0-9' -]+/", $haystack));
return count($result);
}
$database_column_value = 'email,sms,call';
$find_array = ['sms', 'email', 'phone'];
$found_array_times = contains($find_array, $database_column_value);
if ($found_array_times) {
echo "Found times: {$found_array_times}";
} else {
echo "not found";
}
输出:
Found times: 2
如何搭配?预期的有效输入:
email-sms-call
或
sms,email,call
或
sms email call
或
smsemailcall
只有在
之间有 space 时才会匹配<?php
function contains($needles, $haystack) {
return count(
array_intersect(
$needles,
explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $haystack))
)
);
}
$database_column_value = 'email,sms,call';
$find_array = array('sms', 'email');
$found_array_times = contains($find_array, $database_column_value);
if($found_array_times) {
echo "Found times: {$found_array_times}";
}
else {
echo "not found";
}
?>
function contains_word($word, $text)
{
return null!==strpos($word,$text);
}
function count_keyWords($keyWords, $input) {
$numKeyWords=0;
foreach ($keyWords as $word) {
if(contains_word($word, $input)) {
$numKeyWords++;
}
}
return $numKeyWords;
}
//Usage
$input="sms,email,call";
$keyWords=['sms', 'email', 'call'];
$numKeywords=count_keyWords($keyWords, $input);
echo $numKeywords." found";
具有preg_split
功能:
function contains($needles, $haystack) {
if (!$needles || !$haystack)
return false;
$result = array_intersect($needles, preg_split("/[^A-Za-z0-9' -]+/", $haystack));
return count($result);
}
$database_column_value = 'email,sms,call';
$find_array = ['sms', 'email', 'phone'];
$found_array_times = contains($find_array, $database_column_value);
if ($found_array_times) {
echo "Found times: {$found_array_times}";
} else {
echo "not found";
}
输出:
Found times: 2