Jump to content

Regex to grab last pattern only


Monkuar

Recommended Posts

For example:

 

$text = preg_replace_callback( "/([@][a-zA-Z-0-9]+)/"    , "umentions", $text, 1); 
That 1 parameter means the maximum times it will iterate right? So If I'm doing:

 

@Nexus

 

@Cupcake

 

@George

 

it will return:

 

6e36b77e924c4a1c76a982b190123a55.png

 

 

My problem is. I only want it to iterate over the last match in my function:

 

function umentions($matches){
vdump($matches);
    return "(here you would replace: ".$matches[0]." with something)";
}
How is it possible to use limit, and only iterate the last match not the first?
Link to comment
https://forums.phpfreaks.com/topic/294137-regex-to-grab-last-pattern-only/
Share on other sites

How is it possible to use limit, and only iterate the last match not the first?

 

Unless @whatever will always at the end of your your subject string (nothing comes after it) you could use the $ (end) anchor to get the first match from the end of the subject string. 

$text = '@Nexus

@Cupcake

@George';

$text = preg_replace_callback( "/(@[a-zA-Z-0-9]+)$/"    , "umentions", $text, 1); 

The fourth argument is only used to limit how many replacements can take place. It cannot be used to change the order of the matches.

 

 

The alternative way would be use preg_match_all to find all the matches then use end on the array of matches that was returned to get the last match.

Unless @whatever will always at the end of your your subject string (nothing comes after it) you could use the $ (end) anchor to get the first match from the end of the subject string. 

$text = '@Nexus

@Cupcake

@George';

$text = preg_replace_callback( "/(@[a-zA-Z-0-9]+)$/"    , "umentions", $text, 1); 
The fourth argument is only used to limit how many replacements can take place. It cannot be used to change the order of the matches.

 

 

The alternative way would be use preg_match_all to find all the matches then use end on the array of matches that was returned to get the last match.

 

Awesome. Totally forgot about preg_match_all, thank you for the explanation.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.