Parse text between 2 words

后端 未结 5 1312
慢半拍i
慢半拍i 2021-01-20 23:51

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 ha

5条回答
  •  终归单人心
    2021-01-21 00:25

    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]);
        }
    

提交回复
热议问题