user2785693
user2785693

Reputation: 1085

PHP code using preg_replace suddenly quit working last night

The following PHP code was working fine until last night:

// _camelize(sVal, bFirst)
private function _camelize($sVal, $bFirst = false) {
  $sVal = preg_replace("/([_-\s]?([a-z0-9]+))/e", "ucwords('\\2')", $sVal);
  return ($bFirst ? strtolower($sVal[0]) : strtoupper($sVal[0])) . substr($sVal, 1);
}

It no longer works and doing a var_dump on $sVal reveals that null was returned by the call to preg_replace().

I contacted Bluehost and they claim that nothing was done to the (shared) server during the night. I specifically asked if they changed the version of PHP. This was suspect because the documentation for preg_replace specifically mentions that the "\e" modifier is depreciated in PHP 5.5.0 and is removed completely in PHP 7.0.0. CPanel for this account currently indicates PHP 5.4.43 is being used.

I changed the code to the following:

// _camelize(sVal, bFirst)
private function _camelize($sVal, $bFirst = false) {
  $sVal = preg_replace_callback("/([_-\s]?([a-z0-9]+))/", 
    function($matches) {
      return ucwords($matches[2]);
    }, $sVal);

  return ($bFirst ? strtolower($sVal[0]) : strtoupper($sVal[0])) . substr($sVal, 1);
}

This worked on my test server (LAMP on local machine) but still didn't work on the production server.

To get the client's site back up quickly, I ended up ditching the preg_replace call completely and wrote some code which creates and iterates thorugh an array instead.

Can anyone explain what might have happened and why the second example (which uses preg_replace_callback) did not work? Could it have something to do with the Perl libraries?

Thanks for any help

BTW - The intent of this code is to take a string like "do-something-now" and return a string like "doSomethingNow".

Upvotes: 0

Views: 91

Answers (2)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23399

Regex is too complex for something so simple.

function camel_hump($words, $first=false){
    $words = str_replace(" ","",ucwords(strtolower(str_replace("-"," ", $words))));
    return $first ? $words : lcfirst($words);
}
echo camel_hump("these-are-some-words");

check it out here: http://3v4l.org/GNf2u

Upvotes: 0

Mr. Llama
Mr. Llama

Reputation: 20909

It sounds like your host updated PHP to something before 5.4.41.
Your regular expression, ([_-\s]?([a-z0-9]+)), only compiles on version 5.4.40 and prior.

From the patch notes for 5.4.41, we see that the underlying PCRE library was updated:

PCRE:
Upgraded pcrelib to 8.37. (CVE-2015-2325, CVE-2015-2326)


As for your preg_replace_callback, assuming you make the required character class change to [_\s-] it should have worked on every version 5.3.0 onwards.

Upvotes: 1

Related Questions