在 PHP 数组中搜索单词

Search words in PHP Array

我想在 PHP 数组中搜索,值是从 table;

中获取的

例如 字符串是 table;

中的一个字段

字符串值为:

1st Value :- Hello my name is harkesh 
2nd Value :- Last name is Chauhan

while($data = mysql_fetch_array($query))
{
$array[] = $data['string']
}

现在数组正在提取完整的字符串值,但现在我想在 $array[];

中搜索特定的词

例如

如果我输入“Last name”,它应该显示第二个值“Last name is Chauhan”,如果我输入“name”,它应该显示两个值,因为它们都包含 "name"

如何实现..谢谢

可以使用带有 preg_grep() function 的正则表达式来搜索值:

print_r(preg_grep('~\bLast name\b~i', $array));

Array ( 1 => 2nd Value :- Last name is Chauhan )

\b 匹配 word boundary; Used with i (PCRE_CASELESS) flag

Test at eval.in; SO Regex FAQ 获取更多正则表达式信息