How to get a substring between two strings in PHP?
To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.
Input:$string="hey, How are you?" If we need to extract the substring between "How" and "you" then the output should be are Output:"Are" Input:Hey, Welcome to GeeksforGeeks If we need to get the substring between Welcome and for then it should be to geeks as for lies within GeeksforGeeks. Output:" to geeks"
Method 1: Firstly you have to find the ending position of the start word. Then find the starting position of the ending word after that return the substring between those indexes.
Below program illustrate the approach:
Method 2: Using the explode() function. The explode function splits the given string on the basis of the parameter provided i.e. the separator.
This will return an array which will contain the string split on the basis of the separator.
- Split the list on the basis of the starting word.
- In the returned array the 2nd index will contain the words after the start word.
- In the string provided by step 2 if we again split it on the basis of the ending word then the value at first index will be the string between the starting and the ending word.
Below program illustrate the approach
, how are