Parse text between 2 words

parsing, php, regex, string, words

Solution

I'm not much familiar with PHP, but it seems to me that you can use something like:

if (preg_match("/(?<=First).*?(?=Second)/s", $haystack, $result))
    print_r($result[0]);

`(?<=First)` looks behind for `First` but doesn't consume it,

`.*?` Captures everything in between `First` and `Second`,

`(?=Second)` looks ahead for `Second` but doesn't consume it,

The `s` at the end is to make the dot `.` match newlines if any.

To get all the text between those delimiters, you use `preg_match_all` and you can use a loop to get each element:

if (preg_match_all("/(?<=First)(.*?)(?=Second)/s", $haystack, $result))
    for ($i = 1; count($result) > $i; $i++) {
        print_r($result[$i]);
    }

Problem

For sure this has already been asked by someone else, however I've searched here on SO and found nothing https://stackoverflow.com/search?q=php+parse+between+words I have a string and want to get an array with all the words contained between 2 delimiters (2 words). I am not confident with regex so I ended up with this solution, but it is not appropiate because I need to get all the words that match those requirements and not only the first one. ``` $start_limiter = 'First'; $end_limiter = 'Second'; $haystack = $string; # Step 1. Find the start limiter's position $start_pos = strpos($haystack,$start_limiter); if ($start_pos === FALSE) { die("Starting limiter ".$start_limiter." not found in ".$haystack); } # Step 2. Find the ending limiters position, relative to the start position $end_pos = strpos($haystack,$end_limiter,$start_pos); if ($end_pos === FALSE) { die("Ending limiter ".$end_limiter." not found in ".$haystack); } # Step 3. Extract the string between the starting position and ending position # Our starting is the position of the start limiter. To find the string we must take # the ending position of our end limiter and subtract that from the start limiter $needle = substr($haystack, $start_pos+1, ($end_pos-1)-$start_pos); echo "Found $needle"; ``` I thought also about using explode() but I think a regex could be better and faster.

Original source