Search code examples
phpsubstr

How to replace or insert a character on multiple locations on a string using substr_replace, can I add more than one position on the function?


As the title says

I want to insert or replace, a comma ( ,) into a string.

I have this string : A fits B fits C fits D. I want to insert comma behind every fits and right after the word before fits.

This is the desired result : A, fits B, Fits C, Fits D

The code I am using to achieve that is :

$newstr = substr_replace($oldstr,", ",stripos($oldstr,"fits")-1,0);

However, this code only insert 1 comma in the first occurrence of "fits". I tried using substr_count() to get the count of fits occurring and then uses For loop but the comma is stacked in the position of the first occurrence of fits.

like this : A,,, Fits B Fits C Fits D

There must be a way to achieve the desired result, it has to be with adding more than one position in substr_replace() function or something right?

EDIT

The string I have is White Fits Black Fits Red Fits Blue The desired result is White, Fits Black, Fits Red, Fits Blue

The comma , is placed behind every Fits word in the string AND right after the word behind fits

the key point of my question is : How to put comma in behind every fits word AND right after the word behind fits

Thanks before


Solution

  • Use preg_replace:

    $input = "A fits B Fits C Fits D";
    $output = preg_replace("/\b([A-Z]+)(?=\s)/", "$1,", $input);
    echo $input . "\n" . $output;
    

    This prints:

    A fits B Fits C Fits D
    A, fits B, Fits C, Fits D
    

    Here is an explanation of the regex pattern:

    \b([A-Z]+) match AND capture one or more uppercase letters, which are preceded by a word boundary (?=\s) then assert that what follows is a space; this prevents a final letter from being assigned a comma, should the input end in a letter

    Then, we replace with $1, the captured letter(s), followed by a comma.

    Edit:

    For your recent edit, you may use:

    $input = "White Fits Black Fits Red Fits Blue";
    $output = preg_replace("/\b(?=\s+Fits\b)/", ",", $input);
    echo $input . "\n" . $output;
    

    This prints:

    White Fits Black Fits Red Fits Blue
    White, Fits Black, Fits Red, Fits Blue