0

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

3 Answers 3

6

You need preg_quote

Sign up to request clarification or add additional context in comments.

Comments

5

You have to escape braces. You can do that with preg_quote().

$entity = preg_quote($entity, '/');

http://www.php.net/manual/en/function.preg-quote.php

Comments

4

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.