Home  >  Article  >  Backend Development  >  How to replace the last character of a string in php

How to replace the last character of a string in php

藏色散人
藏色散人Original
2020-08-07 10:09:574913browse

php method to replace the last character of a string: first use the "substr" function or "mb_substr" in PHP to intercept the string to the last character; then splice the data you want or use "preg_replace" The method completes the replacement.

How to replace the last character of a string in php

Recommendation: "PHP Video Tutorial"

Example:

可以有很多种实现:
1、使用substr方法(或mb_substr)截取至倒数一位,然后拼接自己想要的数据
 
2、使用$str = preg_replace('#.$#i', '要替换的字符', $str);替换
 
举一反三,自己还可想想其他实现方法。

Related introduction:

substr() function returns a part of a string.

Note: If the start parameter is negative and length is less than or equal to start, length is 0.

Syntax

substr(string,start,length)

The preg_replace function performs a regular expression search and replacement.

Syntax

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

Search for the part of subject that matches pattern and replace it with replacement.

Parameter description:

$pattern: The pattern to be searched, which can be a string or a string array.

$replacement: String or array of strings used for replacement.

$subject: The target string or string array to be searched and replaced.

$limit: Optional, the maximum number of substitutions for each subject string per pattern. The default is -1 (no limit).

$count: Optional, the number of times the replacement is performed.

The above is the detailed content of How to replace the last character 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