Search code examples
phpregexpreg-match

How to use | operator in preg_match for searching between strings?


I've seen many answers, but none seem to help me with my situation. I need to extract the comments from this text:

Comments: These are the comments and they end at this full stop. Remember, you can only use the personal information...

OR this text:

Comments: These are the comments and they end at this full stop. You can only use the personal information...

A working example is here: https://regex101.com/r/apIT0O/1

But I can't seem to get this into PHP. I can get one to work with:

$pattern = "/(?<=Comments: )(.*?)(?= Remember, you can)/s";

But what is wrong with this?

$pattern = "/(?<=Comments: )(.*?)(?= Remember, you can)|(?<=Comments: )(.*?)(?= You can)/s";

Many thanks!


Solution

  • With preg_match_all you can get all result with your regex.

    Try this:

    /(?<=Comments: )(.*?)(?= Remember, you can)|(?<=Comments: )(.*?)(?= You can)/s
    

    Explanation

    Sample Code:

    <?php
    
    $re = '/(?<=Comments: )(.*?).(?= Remember, you can)|(?<=Comments: )(.*?)(?= You can)/sm';
    $str = 'Comments: These are the comments and they end at this full stop. Remember, you can only use the personal information...
    
    Comments: These are the comments and they end at this full stop. You can only use the personal information...';
    preg_match_all($re, $str, $matches);
    print_r($matches);
    ?>
    

    Runt it here