Home > Article > Backend Development > How to delete a certain character in a string in php
Method to delete characters: 1. Use str_replace() function, syntax "str_replace(specified character,'', $str)"; 2. Use substr_replace() function, syntax "substr_replace($str,' ',Specify the position of the character,1)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php delete string Method for a certain character in
Method 1: Delete the specified character
In PHP, str_ireplace() and str_replace use a new string Replace the specific string (character) specified in the original string; when the replacement value is set to the empty character ''
, the specific character is deleted.
Note: str_replace is case-sensitive, str_ireplace() is not case-sensitive.
Example 1: Use str_replace() function
<?php $str = 'abcdefgAC'; $replace = ''; $search1 = 'a'; $search2 = 'A'; echo str_replace($search1, $replace, $str)."<br>"; echo str_replace($search2, $replace, $str)."<br>"; ?>
Output result:
bcdefgAC abcdefgC
Example 2: Use str_ireplace() function
<?php $str = 'abcdefgAC'; $replace = ''; $search1 = 'a'; $search2 = 'A'; echo str_ireplace($search1, $replace, $str)."<br>"; echo str_ireplace($search2, $replace, $str)."<br>"; ?>
Output Result:
bcdefgC bcdefgC
Method 2: Delete the characters at the specified position
substr_replace() function replaces part of the string with another string.
The syntax of the substr_replace() function is as follows:
mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )
substr_replace() Replaces the substring qualified by the start and optional length parameters in a copy of the string string using replacement. If the replacement value is the null character '', characters of length length can be deleted.
Example:
<?php $str = 'abcdefgAC'; $replace = ''; echo substr_replace($str, $replace, 0,1)."<br>"; echo substr_replace($str, $replace, 1,1)."<br>"; echo substr_replace($str, $replace, 2,1)."<br>"; echo substr_replace($str, $replace, 3,1)."<br>"; echo substr_replace($str, $replace, 4,1)."<br>"; echo substr_replace($str, $replace, 5,1)."<br>"; ?>
Output result:
##Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete a certain character in a string in php. For more information, please follow other related articles on the PHP Chinese website!