How to replace the characters in fixed positions in PHP?

后端 未结 7 1692
清歌不尽
清歌不尽 2020-12-11 07:43

I want to replace with the 4~8 characters of a string with *,how to do it?

HelloWorld

=>

Hell****ld
相关标签:
7条回答
  • 2020-12-11 08:23
    $str="HelloWorld";
    print preg_replace("/^(....)....(.*)/","\\1****\\2",$str);
    
    0 讨论(0)
  • 2020-12-11 08:26
    <?php
    $e=str_split("HelloWorld");
    $e[3]="*";
    $e[4]="*";
    $e[5]="*";
    echo implode($e);
    ?>
    

    User can change only the characters that he need.

    0 讨论(0)
  • 2020-12-11 08:27

    use

    substr_replace()
    

    like

    substr_replace($string, '****', 4 , 4);
    

    read more :

    http://php.net/manual/en/function.substr-replace.php

    0 讨论(0)
  • 2020-12-11 08:37
    $string = 'HelloWorld';
    
    for ($i = 4; $i <= 8; ++$i) {
        $string[$i] = '*';
    }
    

    But there is many, many more ways to do that.

    0 讨论(0)
  • 2020-12-11 08:38
    <?php
    $var="HelloWorld";
    $pattern="/oWor/";
    $replace="****";
    echo preg_replace($pattern,$replace,$var);
    ?>
    
    0 讨论(0)
  • 2020-12-11 08:38

    You'll need to use substr_replace().

    $str = substr_replace("HelloWorld","****",3,-2);
    
    0 讨论(0)
提交回复
热议问题