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

How to replace spaces in php (code)

不言
不言 forward
2018-10-12 14:58:00 6351browse

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=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'

=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!

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