Home  >  Article  >  Backend Development  >  How to remove '-' character from php string

How to remove '-' character from php string

青灯夜游
青灯夜游Original
2022-05-31 15:36:182124browse

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.

How to remove '-' character from php string

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$str="1-2-3-4-5-6-7-8";
echo "原字符串:".$str."<br><br>";
echo "去掉&#39;-&#39;字符后:<br>";
echo str_replace("-",&#39;&#39;,$str)."<br>";
echo str_ireplace("-",&#39;&#39;,$str)."<br>";
?>

How to remove - character from php string

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$str="1-2-3-4-5-6-7-8";
echo "原字符串:".$str."<br><br>";
echo "去掉&#39;-&#39;字符后:".preg_replace("/-/", "", $str)."<br>";
?>

How to remove - character from php string

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$str="1-2-3-4-5-6-7-8-9-";
echo "原字符串:".$str."<br><br>";
echo "去掉&#39;-&#39;字符后:".preg_filter("/-/", "", $str)."<br>";
?>

How to remove - character from php string

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!

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