Home > Backend Development > PHP Problem > How to replace intermediate strings in php

How to replace intermediate strings in php

藏色散人
Release: 2023-03-09 19:04:02
Original
2884 people have browsed it

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

Replace part of the string with another string

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

Specify the string repeatedly The number of times

mb_strlen
Copy after login

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

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

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!

Related labels:
php
source:php.cn
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