Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you replace all instances of a pattern with a specific string?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading