Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace not replace exactly in php

$string = '45N654345W124R3546M';
echo preg_replace('/(\w{2})(\w{2})(\w{2})(\w{4})(\w{4})(\w{4})((\w{1})?)/','$1-$2-$3-$4-$5-$6+$7',$string);

Result is Good: 45-N6-54-345W-124R-3546+M

$string = '45N654345W124R3546';
echo preg_replace('/(\w{2})(\w{2})(\w{2})(\w{4})(\w{4})(\w{4})((\w{1})?)/','$1-$2-$3-$4-$5-$6+$7',$string);

Result is Bad: 45-N6-54-345W-124R-3546+ I need return 45-N6-54-345W-124R-3546 with out + What can i do? realmente hablo español XD pero el ingles igual lo entiendo.! there any way to validate the result, say $ 7 brings information to add to the result + $ 7 if you come empty not add anything.

like image 802
Jesus Marquez Avatar asked Aug 05 '26 18:08

Jesus Marquez


1 Answers

You need to check if the last group got matched. For that you could use preg_replace_callback and manipulate the matches however you want. Here's an example of what you could do with it:

preg_replace_callback('/(\w{2})(\w{2})/',
    function($groupings){return empty($groupings[2]) ? $groupings[1]:$groupings[1].'+'.$groupings[2];},
    $string);

That would append the match at index 2 only if it actually got matched.

like image 147
clinch Avatar answered Aug 08 '26 12:08

clinch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!