简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM