2

I'm need to replace string with some pattern in array if needed pattern exists:

$patterns = [
   'PATTERN#1' => 'REPLACE#1',
   'PATTERN#2' => 'REPLACE#2',
];

$string = 'SOME STRING TO PREG_REPLACE';

Which way will be faster:

// PREG_REPLACE ONLY FOR MATCHED PATTERN:
foreach ($patterns as $pattern => $replace) {
    if (preg_match($string, $pattern)) {
        preg_replace($pattern, $replace, $string);
        break;
    }
}

or

// PREG_REPLACE FOR ALL PATTERNS:
foreach ($patterns as $pattern => $replace) {
    preg_replace($pattern, $replace, $string);
    break;
}
2
  • Only replace will be faster - it doesn't need to match twice. Have you tested it? Is the simpler solution too slow? Commented Mar 31, 2013 at 15:04
  • Why do you break; the loop after the first pattern? Commented Mar 31, 2013 at 15:05

1 Answer 1

4

preg_replace takes array arguments for pattern and replacement.

preg_replace(array_keys($patters), array_values($patterns), $string);
Sign up to request clarification or add additional context in comments.

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.