Input:$string = "hey, How are you?" If we need to extract the substring between "How" and "you" then the output should be Output:"Are" Input:Hey, Welcome to GeeksforGeeks If we need to get the substring between Welcome and for then it should be to engineer as for lies within GeeksforGeeks. Output:"to engineer"Method 1: Firstyou must find the ending position of the start word. Then find the starting position of the ending word, and then return the substring between those indices.
The program below illustrates the approach:Program :
function
string_between_two_string (
$str
,
$starting_word
,
$ending_word
)
{
$subtring_start
=
strpos
(
$str
,
$starting_word
);
// Add a word stratification index to
// its length will give the final index
$subtring_start
+ =
strlen
(
$starting_word
);
// The length of our required substring
$size
=
strpos
(
$str
,
$ending_word
,
$subtring_start
) -
$subtring_start
;
// Returns a substring from the substring_start index of length size
return
substr
(
$str
,
$subtring_start
,
$size
);
}
$str
=
’Hey, Welcome to engineerforengineer’
;
$substring
= string_between_two_string (
$str
,
’Welcome’
,
’ for’
);
echo
$substring
;
?>
Output:to engineer
Method 2:using the explode() function. The explode function splits the given string based on the supplied parameter, that is, the delimiter.
Syntax:$arr = explode (separator, string).
This will return an array that will contain the split string based on the separator. - Split the list based on the start word.
- In the returned array, the second index will contain the words after the start word.
- On the line provided in step 2 if we split it again based on the end word, then the value at the first index is the string between the start and end word.
The program below illustrates the approachThe program :
function
string_between_two_string (
$str
,
$starting_word
,
$ending_word
) {
$arr
=
explode
(
$starting_word
,
$str
);
if
(isset ( $arr
[1])) {
$arr
=
explode
(
$ending_word
,
$arr
[1]);
return
$arr
[0];
}
return
’ ’
;
}
$str
=
"Hey, how are you?"
;
$start
=
"Hey"
;
$end
=
"you"
;
$substring
= string_between_two_string (
$str
,
$start
,
$end
);
echo
$substring
;
?>
Output:, how are