在 PHP 的关联数组中搜索与键匹配的子字符串的最简单方法是什么?
What is the simplest way to search a string for a substring matching a key in an associative array in PHP?
我是 PHP 的新手,我需要一个函数来检查用户输入的字符串是否包含与关联数组中的键匹配的子字符串。
到目前为止,我一直在使用 array_key_exists() 函数来检查输入是否~匹配~数组中的键,但我不知道如何去做,除非我一次搜索每个键。也许某种循环会有用?
我的代码看起来像这样:
<form method="post" autocomplete="off">
<textarea id="wiyetxt" name="input"></textarea>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
$input = $_POST["input"];
$keywords = ["apple" => "Found 'apple'", "banana" => "Found 'banana'",
"carrot" => "Found 'carrot'"];
if ($input contains one of these keys) {
echo(value which corresponds to the key);
}
else {
echo("No keys were found");
}
一个foreach
循环搜索所有关键字,如果键值存在于$input中,打印键值。
$keywords = ["apple" => "Found 'apple'", "banana" => "Found 'banana'", "carrot" => "Found 'carrot'"];
foreach ($keywords as $k => $v)
{
if (strstr($input, $k))
print $v;
}
我是 PHP 的新手,我需要一个函数来检查用户输入的字符串是否包含与关联数组中的键匹配的子字符串。
到目前为止,我一直在使用 array_key_exists() 函数来检查输入是否~匹配~数组中的键,但我不知道如何去做,除非我一次搜索每个键。也许某种循环会有用?
我的代码看起来像这样:
<form method="post" autocomplete="off">
<textarea id="wiyetxt" name="input"></textarea>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
$input = $_POST["input"];
$keywords = ["apple" => "Found 'apple'", "banana" => "Found 'banana'",
"carrot" => "Found 'carrot'"];
if ($input contains one of these keys) {
echo(value which corresponds to the key);
}
else {
echo("No keys were found");
}
一个foreach
循环搜索所有关键字,如果键值存在于$input中,打印键值。
$keywords = ["apple" => "Found 'apple'", "banana" => "Found 'banana'", "carrot" => "Found 'carrot'"];
foreach ($keywords as $k => $v)
{
if (strstr($input, $k))
print $v;
}