0

I am trying to do preg_replace to replace underscore convention to camel case, but the ID needs to have always D uppercase, so e.g. from order_address_id to orderAddressID.

My code looks like below:

$patterns = array(
    '#(' . $pregQuotedSeparator.')([A-Za-z]{1})#',
'#(^[id]{2})|([Id]{2})#',
);

$replacements = array(
    function ($matches) {
        return strtoupper($matches[2]);
    },
    function ($matches) {
        return strtoupper('ID');
    },
);


$filtered = $value;

foreach ($patterns as $index => $pattern) {
    $filtered = preg_replace_callback($pattern, $replacements[$index], $filtered);
}

But I don't know why, it is changing to orderAIDressID?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Marek
  • 440
  • 2
  • 6
  • 18
  • The linked question is about dashes, I assume you can figure out how to use the same solution for underscores. – Barmar Aug 29 '14 at 13:08
  • @Barmar, he need last 2 characters caps – Ram Sharma Aug 29 '14 at 13:13
  • That seems like a simple step he can do after converting to camelcase, replace `Id` at the end with `ID`. – Barmar Aug 29 '14 at 13:16
  • @Bamar , as Ram Sharma said already... this is totally different case as you can see I have done already underscores to camel case. The problem is the D – Marek Aug 29 '14 at 13:18
  • @Barmar: This is not a duplicate question, since it need to deal with the particular case of the word "id". Note that this question may be considered as a duplicate more or less only with the approach you suggest that needs to parse the string two times. That is not the case in my answer. – Casimir et Hippolyte Aug 29 '14 at 13:23

1 Answers1

0

You can use this pattern:

_(id(?![a-z])|[a-z])

The "id" word is tested first, if it is not found only the first letter is captured.

Note that the capture number is 1.

$pattern = '~_(id(?![a-z])|[a-z])~i';
$filtered = preg_replace_callback($pattern,
                                  function ($m) { return strtoupper($m[1]); },
                                  $filtered);
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125