【问题标题】:php advanced search in stringsphp在字符串中的高级搜索
【发布时间】:2013-02-23 20:24:57
【问题描述】:

我是 php 新手 也许以前有人问过这个问题,但我不知道具体要搜索什么 无论如何,这是问题

如果我有一个像

这样的字符串
   $adam = "this is a very long long string in here and has a lot of words";

我想在这个字符串中搜索第一次出现的单词“long” 还有“这里”这个词

然后选择它们之间的所有内容,并将其存储在一个新字符串中

所以结果应该是

 $new_string = "long long string in here"

顺便说一句,我不知道字符串的长度和内容,我只知道它有这个词 “长” 和“这里”这个词,我想要它们之间的词..

【问题讨论】:

  • 我不知道,就像我说我是 php 新手,我不知道要搜索什么。我尝试了正则表达式,但似乎没有答案,也搜索了不够具体的高级搜索……所以呢?

标签: php string search


【解决方案1】:

使用这些功能来做到这一点:

  • strpos() - 用它来搜索字符串中的单词
  • substr() - 用它来“剪断”你的字符串
  • strlen() - 使用它来获取字符串长度

找到'long''word'的位置,并使用substr剪切你的字符串。

【讨论】:

  • 所以为了清楚起见,我必须使用 strpos(); 定位第一个单词的出现位置,然后找到第二个单词的出现位置;然后通过 substr() 创建新字符串;但是我应该如何处理 strlen()?
  • 赞成,因为 Peter 为您提供了完成任务可能需要的所有工具。他不是简单地给你解决方案,这不是堆栈溢出的意义所在。您应该首先尝试解决方案,然后要求更多说明。
【解决方案2】:

简单的strpossubstrstrlen 就能解决问题

您的代码可能如下所示

$adam = "this is a very long long string in here and has a lot of words";
$word1="long";
$word2="here";

$first = strpos($adam, $word1);
$second = strpos($adam, $word2);

if ($first < $second) {
    $result = substr($adam, $first, $second + strlen($word2) - $first);
}

echo $result;

这是working example

【讨论】:

    【解决方案3】:

    这是你的脚本,可以复制粘贴了;)

    $begin=stripos($adam,"long");  //find the 1st position of the word "long"
    $end=strripos($adam,"here")+4; //find the last position of the word "here" + 4 caraters of "here"
    $length=$end-$begin;
    $your_string=substr($adam,$begin,$length);
    

    【讨论】:

      【解决方案4】:

      这是一种使用正则表达式的方法:

      $string = "this is a very long long string in here and has a lot of words";
      $first = "long";
      $last = "here";
      
      $matches = array();
      
      preg_match('%'.preg_quote($first).'.+'.preg_quote($last).'%', $string, $matches);
      print $matches[0];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-23
        • 1970-01-01
        • 2012-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        相关资源
        最近更新 更多