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

Time:02-03

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 :)

CodePudding user response:

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

CodePudding user response:

This is the way I would solve it...

<?php

$rows = [
    'Blah *-*-*-*-*-*-*-* Blah',
    'Blah *-*-*-*-*-*-*-*-* Blah',
    'Blah *-*-*-*-*-*-*-*-*-*-*-*-* Blah',
];

array_walk($rows, function (&$row)
{
    $row = preg_replace('/^(.*) [*-]  (.*)$/', '$1 *** $2', $row);
});

[*-] is telling the regex to find any number of * or - characters.

Result

Array
(
    [0] => Blah *** Blah
    [1] => Blah *** Blah
    [2] => Blah *** Blah
)

Regex101.com Sandbox

  •  Tags:  
  • Related