当我搜索“银行”时,它应显示以下列表中的Bank-List1,Bank-List2。
铁路列表,银行清单1,银行清单2,教育,电子商务,文章,铁路清单1.
是否有要显示的PHP功能?
我得到了完全匹配的输出。但这种搜索没有结果。
请帮我找到解决方案。
答案 0 :(得分:2)
您可以使用stristr
stristr — Case-insensitive strstr()
<?php // Example from PHP.net
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}
// outputs: "earth" not found in string
?>
因此,对于您的情况,如果您的列表位于名为$values
你可以做到
foreach($values as $value)
{
if(stristr($value, 'bank') !== FALSE)
{
echo $value."<br>";
}
}
答案 1 :(得分:1)
您可以使用 stristr 执行此操作。此函数返回从第一次出现针到结尾的所有haystack。返回匹配的子字符串。如果未找到needle,则返回FALSE。
以下是完整的代码:
<?php
$str="Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1";
$findme="bank";
$tokens= explode(",", $str);
for($i=0;$i<count($tokens);$i++)
{
$trimmed =trim($tokens[$i]);
$pos = stristr($trimmed, $findme);
if ($pos === false) {}
else
{
echo $trimmed.",";
}
}
?>
<强> DEMO 强>
答案 2 :(得分:1)
此解决方案仅对此文本模式有效,如:word1,word2,word3
<?php
$text = 'Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.';
function search_in_text($word, $text){
$parts = explode(", ", $text);
$result = array();
$word = strtolower($word);
foreach($parts as $v){
if(strpos(strtolower($v), $word) !== false){
$result[] = $v;
}
}
if(!empty($result)){
return implode(", ", $result);
}else{
return "not found";
}
}
echo search_in_text("bank", $text);
echo search_in_text("none", $text);
?>
输出:
Bank-List1, Bank-List2
not found