Given the following …
$rows = [
'Blah *-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-* Blah',
'Blah *-*-*-*-*-*-*-*-*-*-*-*-* Blah',
];
… how would I replace that crappy repeating pattern of unknown length with ***, so the result would be …
$result = [
'Blah *** Blah',
'Blah *** Blah',
'Blah *** Blah',
];
I’m entirely unclear on how repeating patterns work in regex. I tried
foreach ($rows as $r) {
echo preg_replace('/[\*\-]{3,}/', '***', $r) .'<br>';
}
and a number of other variations. Is this an easy thing?
EDIT: I spent 30 minutes scouring stackoverflow for an answer, but found it difficult enough figuring out what question to ask. I could find no relevant answer. So any help framing the question would be appreciated as well 🙂
>Solution :
You can give an array to preg_replace() and it will perform the replacement in all the array elements. It returns a new array of the results, it doesn’t modify the array in place.
To match * followed by -, use \*-, not [\*\-]. The latter matches a single character that’s either * or -.
$result = preg_replace('/(\*-){3,}\*/', '***', $rows);