Preg_replace does 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);

      

The 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);

      

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

+3


source to share


1 answer


You need to check if the last group matches. For this, you can use preg_replace_callback

and manipulate 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);

      



This will add a match to the index 2

only if it actually did match.

+1


source







All Articles