Home > Article > Backend Development > How to replace spaces in php (code)
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]==' ' count++ for i=count(str)-1;i>=0;i-- if str[i]!=' ' str[i+2*count]=str[i] else count-- str[i+2*count+1]='%' str[i+2*count+2]='2' str[i+2*count+3]='0'
<?php function replaceSpace($str) { $length=strlen($str);//注意字符串长度的函数 $count=0; for($i=0;$i<$length;$i++){ if($str[$i]==' '){ $count++; } } //倒叙遍历,字符先复制到后面,空格所在位置替换成目标 for($i=$length-1;$i>=0;$i--){ if($str[$i]!=' '){ $str[$i+$count*2]=$str[$i]; }else{ $count--; $str[$i+$count*2]='%'; $str[$i+$count*2+1]='2'; $str[$i+$count*2+2]='0'; } } 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!