繁体   English   中英

php高级搜索字符串

[英]php advanced search in strings

我是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"

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

使用这些功能:

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

简单的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;

这是一个有效的例子

这是你的脚本,准备复制粘贴;)

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

这是使用正则表达式执行此操作的方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM