Remove a certain character from a string in PHP
Method 1: Using str_replace() function
Example 1:
The following source code will remove all the occurrences of hyphens (-) from a phone number string.
<?php $phone = "123-456-7890"; $phone = str_replace('-', '', $phone); echo $phone; ?> Output: 1234567890
Exaple 2:
To remove the occurrences of multiple characters or phrases in a string.
<?php $string = "Apple, (Mango), 'Banana'"; $newstring = str_replace(array("(", ")", "'"), "", $string); echo $newstring; ?> Output: Apple,Mango,Banana
Method 2: Using preg_replace() function
Method 1:
The preg_replace() function performs a regular expression search and replace, and returns a resulting string.
<?php $phone = '123-456-7890'; $phone = preg_replace('/-/', '', $phone); echo $phone; ?> Output: 1234567890
Example 2:
To remove the occurrences of multiple characters in a string using this method, we include them in our regular expression.
<?php $string = "Apple, (Mango), 'Banana]'"; $newstring = preg_replace("/[()']/", "", $string); echo $newstring; ?> Output: Apple,Mango,Banana
Method 3: Using str_split() and implode()
The str_split() function splits a string into an array.
<?php $phone = "123-456-7890"; $phoneArray = str_split($phone); $phoneArray = array_filter($phoneArray, function ($char) { return $char !== '-'; }); $phone = implode('', $phoneArray); echo $phone; ?> Output: 1234567890