Php 在 foreach 中查找字符串

Php find String in foreach

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

这遍历了我数据库的所有用户,我想找到所有让我们说 $um.

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

我该如何完成?

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

$um = "Um";

foreach($users as $user){

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

        echo $user;

    }
}

strpos() returns 是一个字符串位置,因此 return 值 '0' 将匹配字符串的开头。所以,检查 'not false' http://php.net/manual/en/function.strpos.php

你可以使用 preg_match

$um = "Um";
foreach($users as $user){
     if( preg_match( "@$um@", $user, $matches ) ) echo $user;
}
   $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;