How to Remove Commas in PHP
Removing commas with PHP is helpful when you want a string formatted a different way or if commas were accidentally inserted into your string. Two common scenarios where you may want to remove commas are when you have a number formatted like "1,122' and you want to display it like "1122," or if you have a long list of items separated by commas and you want to display the list without the commas. PHP has several string manipulation functions you can use depending on which commas you want removed.
Instructions
-
-
1
Open your PHP source file in a text editor, such as Windows Notepad.
-
2
Create a variable and assign it a string value. For example, "$str = "test, string,";".
-
-
3
Use the "str_replace(search, replace, string)" function if you want to remove all the commas from the string. For example, "$str = str_replace(',', '', $str);" will return "test string."
-
4
Use the "preg_replace(pattern, replacement, string)" function if you only want to remove certain commas from your string. To remove all the commas, use "/[,]/" as the pattern and '' as the replacement string. For example, "$str = preg_replace('/[,]/', '', $str);" will return "test string."
-
5
Use the "trim(string, character)", "ltrim(string, character)" or "rtrim(string, character)" functions if you only want to remove commas from the beginning or end of the string. The "trim" function removes commas from both the beginning and the end. The "ltrim" function only removes commas from the beginning. The "rtrim" function only removes commas from the end. For example, "$str = trim($str, ',');" will return "test, string."
-
6
Save the PHP file.
-
1
Tips & Warnings
PHP code must be contained within "<?php" and "?>" tags.