【问题标题】:Php find String in foreachphp在foreach中查找字符串
【发布时间】:2016-01-25 06:56:32
【问题描述】:

如何在 foreach 中找到突出显示的字符串?

这会遍历我的数据库的所有用户,我想找到所有可以说 $um 的用户。

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

我该如何做到这一点?

【问题讨论】:

  • 看看strposstr_replace。尝试弄清楚如何自己使用它。如果您需要更多帮助,请告诉我们;)
  • 看看这个question
  • 为什么不使用 MySQL 来做检查呢? WHERE user LIKE '%um%'?
  • 为什么在查询中使用这个更好?

标签: php search foreach highlight


【解决方案1】:

实际上,我会在查询中这样做......但是

$um = "Um";

foreach($users as $user){

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

        echo $user;

    }
}

strpos() 返回一个字符串位置,因此返回值 '0' 将匹配字符串开头。所以,检查“不假” http://php.net/manual/en/function.strpos.php

【讨论】:

  • 如果作品涉及具有特殊字符的不同语言,我建议并检查 mb_strpos..
  • 为什么在查询中使用这个更好?
  • 因为它需要循环、测试,并且只会返回您想要显示的结果。
【解决方案2】:

你可以使用preg_match

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

【讨论】:

    【解决方案3】:
       $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;
    

    【讨论】:

    • 好一个。这是直接的答案。
    • 这行得通的唯一原因是它不会为单个字符设置样式,而是对整个单词进行样式化
    猜你喜欢
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多