如何在文本中搜索字符串


How to search for a string in a text?

我想做的是在一个长文本中搜索一个文本/单词,比如:

$txt = 'text das text dss text good text text bad text';

我想在这个$txt中搜索good text,而不使用像stripos()或其他PHP函数,我想在PHP中只使用for,并尽可能减少循环。

我如何通过所有的$txt搜索good text并获得它之后的内容?

<?php
function findRemaining($needle, $haystack) {
  $result = '';
  for ($i = 0, $found = false; isset($haystack[$i]); $i += 1) {
    if (!$found) {
      for ($j = 0; isset($haystack[$i + $j], $needle[$j]); $j += 1) {
        if ($haystack[$i + $j] !== $needle[$j]) {
          continue 2;
        }
      }
      $found = true;
    }
    $result .= $haystack[$i];
  }
  return $result;
}
$haystack = 'text das text dss text good text text bad text';
$needle = 'good text';
// string(23) "good text text bad text"
var_dump(
  findRemaining($needle, $haystack)
);
<?php
  $txt = 'text das text dss text good text text bad text';
  $search = 'good text';
  $pos = -1;
  $i = 0;
  while (isset($txt{$i})) {
    $j = 0;
    $wrong = false;
    while (isset($search{$j})) {
      if ($search{$j} != $txt{$i + $j}) {
        $wrong = true;
        break;
      }
      $j++;
    }
    if (!$wrong) {
      $pos = $i;
      break;
    }
    $i++;
  }
  echo 'Position: '.$pos; // in your case it will return position: 23
?>

试试这个,让我知道。。。

$txt = "text das text dss text good text text bad text";
function search_string($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_string("text", $txt);

您可以在此处使用preg_match。你想要和这个相关的例子吗?