[英]php advanced search in strings
i'm new to php and maybe this question has been asked before but i don't know what to search for specifically anyway here's the question 我是php的新手,也许这个问题之前已被问过,但我不知道该搜索具体是什么,无论如何这里是问题
if i had a string like 如果我有一个字符串
$adam = "this is a very long long string in here and has a lot of words";
i want to search inside this string for the first occurrence of the word "long" and the word "here" 我想在这个字符串中搜索第一个出现的单词“long”和单词“here”
then select them with everything in between, and store it in a new string 然后选择介于两者之间的所有内容,并将其存储在新字符串中
so the result should be 所以结果应该是
$new_string = "long long string in here"
and by the way i wouldn't know the length of the string and the contents, all what i know is that it has the word "long" and the word "here" and i want them with the words in between.. 顺便说一下,我不知道字符串和内容的长度,我所知道的是它有“long”这个词和“here”这个词,我想要它们之间的单词。
Use these functions to do it: 使用这些功能:
find position of 'long' and 'word' , and cut your string using substr
. 找到'long'和'word'的位置 ,并使用
substr
剪切你的字符串。
Simple strpos
, substr
, strlen
will do the trick 简单的
strpos
, substr
, strlen
就可以了
Your code might look like this 您的代码可能如下所示
$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;
Here is a working example 这是一个有效的例子
Here is your script, ready for copy-paste ;) 这是你的脚本,准备复制粘贴;)
$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);
Here's a way of doing that with regular expressions: 这是使用正则表达式执行此操作的方法:
$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.