0

我是 php 的新手,也许以前有人问过这个问题,但我不知道具体要搜索什么,这就是问题所在

如果我有一个像这样的字符串

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

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

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

所以结果应该是

 $new_string = "long long string in here"

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

4

4 回答 4

1

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

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

找到'long''word' 的位置,并使用substr.

于 2013-02-23T20:33:09.997 回答
1

简单strpos,,substrstrlen可以了

您的代码可能如下所示

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

这是一个工作示例

于 2013-02-23T20:39:52.817 回答
0

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

$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);
于 2013-02-23T20:37:25.173 回答
0

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

$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];
于 2013-02-23T20:44:38.773 回答