Jump to content

Regex to grab last pattern only


Monkuar
Go to solution Solved by Ch0cu3r,

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? Edited by Monkuar
Link to comment
Share on other sites

  • Solution
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.

Edited by Ch0cu3r
  • Like 1
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.