Reputation: 13
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 P.M Alice wrote:"
. I want to capture "On Mon 4 P.M 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
Upvotes: 1
Views: 1217
Reputation: 679
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"
Upvotes: 1
Reputation: 785156
You can use this lookahead based regex for last match in your input for preg_match
:
/\bon\b(?:(?!\bon\b).)*?\bwrote\b/i
(?:(?!\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.
Upvotes: 0