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

How to replace spaces in php (code)

不言
Release: 2023-04-04 09:42:02
forward
6450 people have browsed it

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;
Copy after login

<?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);
Copy after login

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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template