Reputation: 4081
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.
Upvotes: 0
Views: 350
Reputation: 92845
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
Upvotes: 1
Reputation: 1645
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];
Upvotes: 0
Reputation: 16943
Use these functions to do it:
find position of 'long' and 'word', and cut your string using substr
.
Upvotes: 1
Reputation: 1047
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);
Upvotes: 0