[英]What is the simplest way to search a string for a substring matching a key in an associative array in PHP?
I'm fairly new to PHP and I need a function that will check if a string input from the user contains a substring matching a key in an associative array. 我对PHP相当陌生,我需要一个函数来检查用户输入的字符串是否包含与关联数组中的键匹配的子字符串。
So far I've been using the array_key_exists() function a lot to check if the input ~matches~ a key in an array, but I don't know how to go about doing this unless I search for each key one at a time. 到目前为止,我已经大量使用array_key_exists()函数来检查输入是否匹配数组中的一个键,但是除非每次一次搜索每个键,否则我不知道该怎么做。 。 Maybe some kind of loop would be useful?
也许某种循环会有用吗?
My code looks something like this: 我的代码如下所示:
<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");
}
A foreach
loop to search all the keywords, if the key value exists within $input, print the key's value. 一个
foreach
循环,用于搜索所有关键字,如果键值存在于$ input中,则打印键的值。
$keywords = ["apple" => "Found 'apple'", "banana" => "Found 'banana'", "carrot" => "Found 'carrot'"];
foreach ($keywords as $k => $v)
{
if (strstr($input, $k))
print $v;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.