Search code examples
phpregexregex-group

Regex detect a sub-string from a string, and replace with white space


Need to detect all the instances of a sub-string of the form "Índice - n -" from a string and replace them with a white space.

Also, "n" can be any positive number and there can be 1 or more spaces before and after the string, and in between words.

I think I can use this function:

$myString = preg_replace( '/\sÍndice\s+/', ' ', $myString );

But I am stuck in the regex expression.

For example:

"This is a sentence Índice - 8 - forever" would become "This is a sentence forever"

"Just do it. Índice - 3 -" would become "Just do it. "

Please help.


Solution

  • You could use this regex:

    Code:

    $arr = [
        "This is a sentence Índice - 8 -    forever",
        "Just do it. Índice - 3 -",
    ];
    foreach ($arr as $str) {
        echo preg_replace('/\h*Índice - \d+ -\h*/', ' ', $str), "\n";
    }
    

    Output:

    This is a sentence forever
    Just do it. 
    

    Demo & explanation