php - add string at offset?

前端 未结 2 1760
不思量自难忘°
不思量自难忘° 2021-01-22 14:17

If I have a string like \"test\", I have characters from offset 0-3. I would like to add another string to this one at offset 6. Is there a simple PHP function that can do this?

相关标签:
2条回答
  • 2021-01-22 15:05

    Convert the string to an array, in the case where the offset is greater than the string length fill in the missing indexes with a padding character of your choice otherwise just insert the string at the corresponding array index position and implode the string array.

    Please see the function below:

    function addStrAtOffset($origStr,$insertStr,$offset,$paddingCha=' ')
    {
        $origStrArr = str_split($origStr,1);
    
        if ($offset >= count($origStrArr))
        {
            for ($i = count($origStrArr) ; $i <= $offset ; $i++)
            {
                if ($i == $offset) $origStrArr[] = $insertStr;
                else $origStrArr[] = $paddingCha;
            }
        }
        else
        {
            $origStrArr[$offset] = $insertStr.$origStrArr[$offset];
        }
    
        return implode($origStrArr);
    }
    
    echo addStrAtOffset('test','new',6);
    
    0 讨论(0)
  • 2021-01-22 15:12

    To solve your problem first of all you convert your strings in arrays with str_split, then when you've got the array you're done, you can perform any kind of operations on these strings.

    Code:

    $s1 = "test";
    $s2 = "new";
    //converting string into array
    $strings[0] = str_split($s1, 1);
    $strings[1] = str_split($s2, 1);
    //setting the first word of sentence
    $sentence = $strings[0];
    //insert every character in the sentence of "new" word
    for ($i=0; $i < count($strings[1]); $i++) { 
        $sentence[] = $strings[1][$i];
    }
    print_r($sentence);
    

    Result:

    Array
    (
        [0] => t
        [1] => e
        [2] => s
        [3] => t
        [4] => n
        [5] => e
        [6] => w
    )
    
    0 讨论(0)
提交回复
热议问题