开发者

Append and Control if a string contains a char in a string x position [recursively]

i have this situation:

$asd = "Hey hello world!";

now i would like to know how can i append (if not exist) recursively(every 3 chars) a char (ex: "J") ... parsing from left to right the string?

so r开发者_开发问答esults will be:

$asd = "HeyJ heJlloJ woJrldJ!";


How about:

$str = "Hey hello world!";
for($i=3; $i<strlen($str); $i+=4) {
    if ($str[$i] != 'J')
        $str = substr_replace($str, 'J', $i, 0);
}
echo $str,"\n";

output:

HeyJ heJlloJ woJrldJ!


You could do it this way:

if(substr($asd, 3, 1) !== 'J')
{
    $asd = substr($asd, 0, 3)."J".substr($asd, 3);

}

Unless you know for a fact the the string $asd is longer than three characters you should also check the length of the string before:

if(strlen($asd) > 3 && substr($asd, 3, 1) !== 'J')
{
    $asd = substr($asd, 0, 3)."J".substr($asd, 3);
}

Finally, the method above works well for both single characters as well as multiple character sequences but if you only care about 1 character you could just use the string index to check if the character is there, like so:

if(strlen($asd) > 3 && $asd[3] !== 'J')
{
    $asd = substr($asd, 0, 3)."J".substr($asd, 3);
}

If you need to do it every 3 charachters just put it in a loop:

$pos = 0;
while(true)
{
    // go to the position of the next character of interest
    $pos += 3;

    // if the next pos is past the end of the string break out of the loop
    if(strlen($asd) <= $pos)
        break;

    if($asd[$pos] !== 'J')
    {
       $asd = substr($asd, 0, $pos)."J".substr($asd, $pos);
       $pos++;
    }
}

NOTE

If the string you are editing this way is large and the number of occurrences that need to be modified is also pretty large you could optimized the algorithm so that it first finds the positions where characters need to be inserted, then splits the original string into an array of sub-strings and then concatenates them all together using the control character as the joiner using array_join

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜