Home > Article > Backend Development > How to remove '-' character from php string
3 methods: 1. Use "str_replace("-",'',$str)" to replace the "-" character with a null character; 2. Use "preg_replace("/-/"," ",$str)" executes a regular expression to find the "-" character and remove it; 3. Use preg_filter() to remove it.
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
Remove the php string "-" character method
Method 1: Use str_replace() or str_replace() function
str_ireplace() and str_replace use new A string replaces a specific string specified in the original string. str_replace is case-sensitive, while str_ireplace() is not case-sensitive. The syntax of the two is similar.
Just replace the "-
" characters with the empty characters ''
.
<?php header('content-type:text/html;charset=utf-8'); $str="1-2-3-4-5-6-7-8"; echo "原字符串:".$str."<br><br>"; echo "去掉'-'字符后:<br>"; echo str_replace("-",'',$str)."<br>"; echo str_ireplace("-",'',$str)."<br>"; ?>
Method 2: Use the preg_replace() function
The preg_replace() function can be used with regular expressions to find all "- ” character and replace it with the empty character ''.
<?php header('content-type:text/html;charset=utf-8'); $str="1-2-3-4-5-6-7-8"; echo "原字符串:".$str."<br><br>"; echo "去掉'-'字符后:".preg_replace("/-/", "", $str)."<br>"; ?>
Method 3: Use the preg_filter() function
Similarly, the preg_filter() function works with regular expressions to find all " -" character and replace it with the empty character ''.
<?php header('content-type:text/html;charset=utf-8'); $str="1-2-3-4-5-6-7-8-9-"; echo "原字符串:".$str."<br><br>"; echo "去掉'-'字符后:".preg_filter("/-/", "", $str)."<br>"; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove '-' character from php string. For more information, please follow other related articles on the PHP Chinese website!