0

According to this SO answer, in any regular expression, I need to escape these characters outside the character classes.

.^$*+?()[{\|

I have the following:

$search = "App::uses('Controller', 'Controller');";

$replace = $search . "\nApp::uses('CrudControllerTrait', 'Crud.Lib');";
$escaped_search = escape_special_characters($search);

$patterns = array('/' . $escaped_search . '/');
$replacements = array($replace);
$file_contents = preg_replace($patterns, $replacements, $file_contents);

The preg_replace will fail because I need to escape the ( inside the $search variable.

Which is why I have this function:

function escape_special_characters($search) {
  $special_characters = array(
    ".", "^", "$", 
    "*", "+", "?",
    "(", ")", "[",
    "{", "|", "\\"
  );

  $character_array = str_split($search);
  $string_array = array();
  foreach ($character_array as $character) {
    if (in_array($character, $special_characters)) {
      $string_array[] = "\\";
    }
    $string_array[] = $character;
  }

  return implode("", $string_array);

}

My question is whether there is a better way to do this other than my escape_special_characters function?

========================================================================

SOME BACKGROUND:

Why did I write my code as such above?

My purpose is to look for the line App::uses('Controller', 'Controller'); and write the line App::uses('CrudControllerTrait', 'Crud.Lib'); AFTER it.

Community
  • 1
  • 1
Kim Stacks
  • 10,202
  • 35
  • 151
  • 282

1 Answers1

1

You don't need to create a function to escape the "ugly dozen" characters in a pattern.

You have two way to do this:

$pattern = '~' . preg_quote($search, '~') . '~'; // to escape special characters and the delimiter

or

$pattern = '~\Q' . $search . '\E~'; // to ignore special characters

However, I don't understand why you use the preg_replace() function instead of the str_replace() function since you seems to look for a literal string.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125