Home  >  Article  >  Backend Development  >  How to replace intermediate strings in php

How to replace intermediate strings in php

藏色散人
藏色散人Original
2021-05-19 09:52:502774browse

How to replace the middle string in php: first create a PHP sample file; then replace the middle string through the "public function encodeStr($str){...}" method.

How to replace intermediate strings in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

php replaces the asterisk in the middle of the string

This involves three string processing functions

substr_replace

Replace part of the string with another string

substr_replace(string,replacement,start,length)
// string必需。规定要检查的字符串。
// replacement必需。规定要插入的字符串。
// start必需。规定在字符串的何处开始替换。
// 正数 - 在字符串中的指定位置开始替换
// 负数 - 在从字符串结尾的指定位置开始替换
// 0 - 在字符串中的第一个字符处开始替换
// length可选。规定要替换多少个字符。默认是与字符串长度相同。
// 正数 - 被替换的字符串长度
// 负数 - 表示待替换的子字符串结尾处距离 string 末端的字符个数。
// 0 - 在字符串中的第一个字符处开始替换
str_repeat

Specify the string repeatedly The number of times

mb_strlen

Returns the length of the string. When it is different from strlen, it can return the corresponding number of characters by setting the character encoding, which solves the problem of the length of the Chinese string very well

mb_substr

Returns a part of the string, similar to the substr() function. It only targets English characters. If you want to split Chinese characters, you need to use mb_substr()

/**
  * 加密字符串
  * addtime 2020年8月18日 14:16:44
  * @param [type] $str 待加密的字符串
  * @return void
  */
public function encodeStr($str)
{
    # 判断字符串长度
    $length = strlen($str);
    if ($length == 1) {
        # 长度为 1 前后拼接 * 号
        $newStr = $str.'*'.rand(1,6);
    }else{
            # 长度超过1随机插入 * 号
            $newStr = substr_replace($str,str_repeat('*',$length/2),ceil($length/2),$length).mb_substr($str,$length-2,$length,"utf-8");
            // str_repeat('*',$length/2)  星号重复字符长度的一半长度
            // ceil($length/2) 算出从第几个字符开始
    }
    return $newStr;
}

Recommended learning: "PHP Video Tutorial

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

Statement:
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