Home  >  Article  >  Backend Development  >  How to replace spaces in php (code)

How to replace spaces in php (code)

不言
不言forward
2018-10-12 14:58:006427browse

The content of this article is about how to replace spaces (code) in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Replace spaces:

Please implement a function to replace each space in a string with " ". For example, when the string is We Are Happy, the replaced string is We Are Happy.

Idea:

1. First loop through and find out the number of " " spaces in the string count

2. Because you need to replace " " spaces with " ", so count backwards, and the elements after the last space should be moved to the 2*count position

3. Continue to traverse forward, and the elements after the second-to-last space until the last space, go to Move after (count-1)*2 position

replaceSpace(str)
    count=0
    for i=0;i<count(str);i++
        if str[i]==&#39; &#39; count++
    for i=count(str)-1;i>=0;i--
        if str[i]!=&#39; &#39;
            str[i+2*count]=str[i]
        else
            count--
            str[i+2*count+1]=&#39;%&#39;
            str[i+2*count+2]=&#39;2&#39;
            str[i+2*count+3]=&#39;0&#39;

<?php
function replaceSpace($str)
{
        $length=strlen($str);//注意字符串长度的函数
        $count=0;
        for($i=0;$i<$length;$i++){
                if($str[$i]==&#39; &#39;){
                        $count++;
                }   
        }   
        //倒叙遍历,字符先复制到后面,空格所在位置替换成目标
        for($i=$length-1;$i>=0;$i--){
                if($str[$i]!=&#39; &#39;){
                        $str[$i+$count*2]=$str[$i];
                }else{
                        $count--;
                        $str[$i+$count*2]=&#39;%&#39;;
                        $str[$i+$count*2+1]=&#39;2&#39;;
                        $str[$i+$count*2+2]=&#39;0&#39;;
                }   
        }   
        return $str;
}
$str="We Are Happy";
$str1=replaceSpace($str);
var_dump($str1);

The above is the detailed content of How to replace spaces in php (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete