如何在foreach中找到突出显示的字符串?
这会遍历我数据库的所有用户,我想找到所有让我们说的美元。
$um = "Um";
foreach($users as $user){
# find here the string um or something
echo $user;
}
我如何做到这一点?
答案 0 :(得分:4)
实际上,我会在查询中执行此操作.. ..但
$um = "Um";
foreach($users as $user){
if(strpos($user,$um) !== false){
echo $user;
}
}
strpos()
返回一个字符串位置,因此返回值“0”将是字符串开头的匹配项。因此,请检查“非虚假” http://php.net/manual/en/function.strpos.php
答案 1 :(得分:4)
$um = "this is string contains um";
$keyword[] = "um"; // the word/parts you wanna highlight
$result = $um;
foreach($keyword as $key) {
$result = str_replace($key, "<strong>$key</strong>", $result);
}
echo $result;
答案 2 :(得分:1)
您可以使用preg_match
$um = "Um";
foreach($users as $user){
if( preg_match( "@$um@", $user, $matches ) ) echo $user;
}