Monkuar Posted January 22, 2015 Share Posted January 22, 2015 (edited) 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: 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 January 22, 2015 by Monkuar Quote Link to comment Share on other sites More sharing options...
Solution Ch0cu3r Posted January 22, 2015 Solution Share Posted January 22, 2015 (edited) 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 January 22, 2015 by Ch0cu3r 1 Quote Link to comment Share on other sites More sharing options...
Monkuar Posted January 22, 2015 Author Share Posted January 22, 2015 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.