Skip to content
Advertisement

I have an array of regex I am replacing with the same character. How would I use or “|” with my regex to lower array count?

I have more setup in my arrays but to keep it simple I’m only placing the ones with which I want to group together using or “|”.

$patterns = array();
$patterns[1] = "/(?::)/";
$patterns[2] = "/(?:-_)/";
$patterns[3] = "/(?:_-)/";
$replacements = array();
$replacements[1] = "-";
$replacements[2] = "-";
$replacements[3] = "-";
preg_replace($patterns, $replacements, $data['string']);

I have tried different attempts with no success. Below is an attempt of grouping the desired array:

$patterns = array();
$patterns[1] = "/(?::|-_|_-|)/";
$replacements = array();
$replacements[1] = "-"

All my other arrays have a unique $replacments. Leaving the original setup works as I want but I simply want to lower the arrays count by grouping these 3 into 1. This regex actually works as intended but for my scenario I had to leave my original setup as was/is.It was giving mixed results because of the order of the replacements. Triggering the replacement in one group gave weird results.

Advertisement

Answer

Since replacement is same - you can combine all your matching regex with | and use a simpler version of preg_replace:

$data['string'] = preg_replace('/(?::|-_|_-|)/', '-', $data['string']); 

Here (?::|-_|_-|) will match a : or -_ or _-.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement