【问题标题】:How to search for a string in a text?如何在文本中搜索字符串?
【发布时间】:2013-11-20 10:06:34
【问题描述】:

我想要做的是在长文本中搜索文本/单词,例如:

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

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

我怎样才能通过所有$txt 搜索good text 并获得它之后的内容?

【问题讨论】:

  • 甚至没有正则表达式函数?
  • 为什么不用php函数????他们有什么问题
  • 让 PHP 跑一场没有腿的马拉松 :)
  • 好的,检查一下 - 我只使用了 whileisset,当然还有 if...

标签: php


【解决方案1】:
<?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)
);

【讨论】:

  • +1 ... 好吧 Yoshi :) 你的回答太棒了!谢谢!你的方法真的很有趣
  • 检查后,带有自定义函数的结果的 var_dump 只返回第一个字母 => 'g' ...
  • 我更改了答案,以举例说明如何收集结果并从函数中返回。
【解决方案2】:
<?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
?>

【讨论】:

  • 感谢您的回答!但我不想使用任何 php 函数来实现这一点,你能在没有 strlen, substr 的情况下做到吗?再次感谢!
  • 在不知道$txt$search 的长度的情况下如何处理for?我可以使用while吗?
  • +1 ... 它工作正常,位置正确,但有一个问题,我怎样才能使显示从该位置到文本末尾:good text text bad text?非常感谢!
  • 大声笑,至少 +1,但甚至不是……+1 来自其他人:D
  • 我投给了你军团士兵。非常感谢您的帮助!
【解决方案3】:

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

$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);

【讨论】:

  • 感谢您的回答,但我需要一个没有 PHP 函数的实现......就像 Yoshi 的回答一样。感谢您的努力!
【解决方案4】:

您可以在此处使用preg_match。您想要与此相关的示例吗?

【讨论】:

  • 感谢您的回答!但只有 isset() 可以使用
猜你喜欢
  • 2011-06-23
  • 2011-09-13
  • 1970-01-01
  • 2017-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多