我们在 PHP 中有一个函数in_array
,它检查给定值是否存在于数组中。我想我想反其道而行之。我有一组字符串:
$words = array("hello", "world");
而且,我想检查给定字符串是否包含这些单词,方法是提供参数是否all
为any
.
$string = "Hello, World!";
$second = "Hello and Welcome!";
in_string($words, $string, "all");
in_string($words, $string, "any");
我现在拥有的是,使用stripos()
. 我不想用regex
.
当前代码:
<?php
/**
* Checks if the given words is found in a string or not.
*
* @param Array $words The array of words to be given.
* @param String $string The string to be checked on.
* @param String $option all - should have all the words in the array. any - should have any of the words in the array
* @return boolean True, if found, False if not found, depending on the $option
*/
function in_string ($words, $string, $option)
{
if ($option == "all")
foreach ($words as $value)
$isFound = $isFound && (stripos($string, $value) || false);
else
foreach ($words as $value)
$isFound = $isFound || (stripos($string, $value) || false);
return $isFound;
}
?>
我的问题是,这可以改进吗?有什么想法吗?
更新 #1:当前代码更新:
/**
* Checks if the given words is found in a string or not.
*
* @param Array $words The array of words to be given.
* @param String $string The string to be checked on.
* @param String $option all - should have all the words in the array. any - should have any of the words in the array
* @return boolean True, if found, False if not found, depending on the $option
*/
function in_string ($words, $string, $option)
{
if ($option == "all")
{
$isFound = true;
foreach ($words as $value)
$isFound = $isFound && (stripos($string, $value) !== false);
return $isFound;
}
else
{
$isFound = true;
foreach ($words as $value)
if (stripos($string, $value) !== false) return true;
return $isFound;
}
}
现在该功能按预期工作。但我需要在foreach()
部分和所有方面有更好的表现。有什么可以改进的地方吗?
更新 #2:增加了改进
<?php
/**
* Checks if the given words is found in a string or not.
*
* @param Array $words The array of words to be given.
* @param String $string The string to be checked on.
* @param String $option all - should have all the words in the array. any - should have any of the words in the array
* @return boolean True, if found, False if not found, depending on the $option
*/
function in_string ($words, $string, $option)
{
if ($option == "all")
{
foreach ($words as $value)
if (stripos($string, $value) === false)
return false;
return true;
}
else
{
foreach ($words as $value)
if (stripos($string, $value) !== false)
return true;
return false;
}
}
?>