Home  >  Article  >  Backend Development  >  How to replace part of a string in php

How to replace part of a string in php

藏色散人
藏色散人Original
2020-10-05 09:06:202573browse

How to replace part of a string in php: First create a PHP sample file; then use the "str_replace" function to replace the specified string.

How to replace part of a string in php

Recommendation: "PHP Video Tutorial"

PHP replaces the specified string

Use str_replace Replace the specified string

$param = '香蕉皮是什么垃圾';
$pattone = [
            '是什么垃圾',
            '是啥垃圾',
            '属于什么垃圾',
            '算什么垃圾',
            '属于啥垃圾',
            '算啥垃圾',
 ];
 $new_param = str_replace($pattone, '*', $param);
$param = '香蕉皮是哪类垃圾';
$patttwo = [   //字数多的放在前面优先匹配
            '是不是',
            '垃圾吗',
            '属不属于',
            '算不算',
            '哪一种',
            '哪一类',
            '哪种',
            '哪类',
            '属于',
            '一种',
            '垃圾',
            '什么',
            '算',
            '啥',
            '是',
        ];
        $new_param = str_replace($patttwo, '*', $param);

Use the regular method, the string function is faster than the regular

$param = '香蕉皮是哪类垃圾';
$patt = '/是不是|属不属于|算不算|垃圾|是|算|啥|什么|属于|哪类/';
$new_param = preg_replace($patt, '*', $param);

The above is the detailed content of How to replace part of a string 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