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
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"
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..
Simple strpos
, substr
, strlen
will do the trick
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];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.