peace_love
peace_love

Reputation: 6461

How can I insert a string into a string after specific characters?

$string = 'blue*green-yellow-orange/rosa*white+lila';

$calcSigns = '+-*/';

$addstring = 'color1';

Whenever there is a calculation Sign I want to add after the calculation sign the string "color-1".

The result, that I am trying to achieve is:

blue*color-1green-color-1yellow-color-1orange/color-1rosa*color-1white+color-1lila

This is my approach:

$result =  substr_replace($string, $addstring, $calcSigns);

But I do not get the correct result.

Upvotes: 0

Views: 356

Answers (1)

nice_dev
nice_dev

Reputation: 17805

substr_replace() would make it tricky to preserve the current operation character while replacing. You could instead loop through each character and create a new string out of it.

<?php

    $len = strlen( $string );
    $new_string = '';
    for( $i=0; $i<$len; ++$i ) {
        $new_string .= $string[$i];
        if( in_array( $string[$i], ['+','-','*','/'] ) ) {
            $new_string .= $addstring;
        }
    }

    echo $new_string;
?>

Demo: https://3v4l.org/P5tVr

Update:

So, if a operation character is immediately succeeded by a digit and if you want to skip it, and insert addString otherwise, it would look something like below:

<?php


$string = 'blue+yellow*3-grey+orange';

$calcSigns = '+-*/';

$addstring = 'color1';


$len = strlen($string);
$new_string = '';
for($i=0;$i<$len;++$i){
    $new_string .= $string[$i];
    if(in_array($string[$i],['+','-','*','/'])){
        if($i + 1 < $len && is_numeric($string[$i + 1])) continue;
        $new_string .= $addstring;
    }
}


echo $new_string;

Demo: https://3v4l.org/uQobj

Upvotes: 3

Related Questions