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.