简体   繁体   中英

Find the last occurrence using Regular Expressions

I'm a regex newbie, please help me out. The string below occurs in one document:

not_unique\\">20,000 miles under sea

I need to extract the number. The sequence "not_unique" is not unique and may occur in the whole document several times before this sample comes. The part "miles under sea" is unique for the document, can be used as ending delimiter.

I tried something like this in PHP, but it didn't work for me:

if (preg_match('/(?=.*?miles under sea)(?!.+?not_unique)not_unique/', $document, $regs)) {...}

Please help!

How about something like this?

<?php

$document = "blah blah blah sjhsdijf  not_unique\">20,000 miles under sea</a> jkdjksds  sdsjdlksdsd k skdjsld sd";

//the made optional, also account for 'leagues' instead of miles

preg_match("/([0-9,]{1,6})\s?(miles|leagues)\sunder(\sthe)?\ssea/i", $document, $matches);

print_r($matches);

?>

/ not unique\\">\\s*([0123456789,]+)\\s*miles under the sea /

should do it.

This should do the trick:

preg_match_all('/[1234567890\,]+ miles under sea/i', 'not_unique\">20,000 miles under sea', $result); //find all occurances of the pattern
$tempval=$result[sizeof($result)-1]; //get the last one
$endresult=substr($tempval,0,strlen($tempval)-16); //get the string without the length of the ending string

If needed - replace 16 with the exact length of the ending string.

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