I have an array of entities that need to be replaced in a large sting but only the first occurrence of each (this is why I am using preg_replace
rather than str_replace
), e.g.:
$entities = array();
$entities[0] = 'string1';
$entities[1] = 'string2';
$entities[2] = 'string2';
$entities[3] = 'Error String ('; ## this is the one that errors because of the bracket
$entities[4] = 'string4';
$entities[5] = 'string5';
foreach ($entities as $entity) {
$new_article = preg_replace('/' . $entity . '/', '##' . $key, $new_article, 1);
}
I am getting the following error:
Warning (2): preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset XX
What is the best way to get the bracket escaped, and also escape any other character that might be used in regex.
Thanks
You need preg_quote
You have to escape braces. You can do that with preg_quote()
.
$entity = preg_quote($entity, '/');
You can use preg_quote
$entities = array();
$entities[0] = 'string1';
$entities[1] = 'string2';
$entities[2] = 'string2';
$entities[3] = 'Error String ('; ## this is the one that errors because of the bracket
$entities[4] = 'string4';
$entities[5] = 'string5';
foreach ($entities as $entity) {
$new_article = preg_replace('/' . preg_quote($entity) . '/', '##' . $key, $new_article, 1);
}