2015-10-26 64 views
1

如何在foreach中找到一个高亮字符串?PHP在foreach中查找字符串

这循环遍历我的数据库的所有用户,我想找到所有可以说$美元。

$um = "Um"; 
foreach($users as $user){ 
    # find here the string um or something 
    echo $user; 
} 

我该如何做到这一点?

+0

看看[strpos(http://php.net/manual/en/function.strpos .php)和[str_replace](http://php.net/manual/en/function.str-replace.php)。尝试弄清楚如何自己使用它。如果你需要更多的帮助,让我们知道;) –

+0

看看这个[问题](http://stackoverflow.com/questions/17422370/highlight-only-typed-keywords-from-string-in-php)。 – Thaillie

+1

为什么不使用MySQL来做检查? '用户喜欢'%um%'? –

回答

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; 
+0

好的。这是直接的答案。 –

+0

这有效的唯一的事情是,它没有风格的单个字符只是完整的单词 – Slark

4

在现实中,我会在查询做.. ..但

$um = "Um"; 

foreach($users as $user){ 

    if(strpos($user,$um) !== false){ 

     echo $user; 

    } 
} 

strpos()返回一个字符串的位置,这样的“0”返回值是在的开头匹配串。所以,检查是否有 '不假'http://php.net/manual/en/function.strpos.php

+0

我推荐并检查mb_strpos,如果工作涉及具有特殊字符的不同语言。 – Svetoslav

+0

为什么在查询中使用它会更好? – Slark

+0

因为它需要循环和测试,并且只返回想要显示的结果。 – MaggsWeb

1

你可以使用preg_match

$um = "Um"; 
foreach($users as $user){ 
    if(preg_match("@[email protected]", $user, $matches)) echo $user; 
}