简体   繁体   中英

PHP preg_match starting from end of string

I'm trying to capture a string pattern but starting from the end of the string.

If I have a string like:

"Hi, I saw you on tv yesterday. On Mon 4 P.M Alice wrote:"

A regular preg_match that captures everything between word "on" and word "wrote:" will capture "on tv yesterday. On Mon 4 PM Alice wrote:" . I want to capture "On Mon 4 PM Alice wrote:" .

I can't solve it with preg_match_all as it will just match the first one.

My pattern:

/(<div>|<br>|<br \/>|<br\/>)\s*on\s(.*)wrote:/i

I also tried to solve it with strrpos but it doesn't respect spaces.

Thanks, Martin

You can use this lookahead based regex for last match in your input for preg_match :

/\bon\b(?:(?!\bon\b).)*?\bwrote\b/i

RegEx Demo

(?:(?!\\bon\\b).)*? is negative lookahead based regex that will match text between on and wrote when on doesn't appear between them thus making sure to match last match in input.

I think the best solution would be to use these nice functions I found here . Personally I use it quite often, and it never let me down.

<?php    
function strrevpos($instr, $needle)
    {
        $rev_pos = strpos (strrev($instr), strrev($needle));
        if ($rev_pos===false) return false;
        else return strlen($instr) - $rev_pos - strlen($needle);
    };
     function before ($this, $inthat)
        {
            return substr($inthat, 0, strpos($inthat, $this));
        };
     function between ($this, $that, $inthat)
        {
            return before ($that, after($this, $inthat));
        };
?>

You can then just easily do:

$string = 'Hi, I saw you on tv yesterday. On Mon 4 P.M Alice wrote:"';
$result = between ('On', 'wrote:', $string);
echo $result; //should echo "Mon 4 P.M Alice"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM