In this article explained of php remove numbers from string example. If you want to see an example of php remove all numbers from string then to get best example here. you will learn php remove numbers from string. You can easily understand a concept of remove numbers from string php.
There are several method to remove numbers from string value in php. I will explain with you.
Let’see method for remove numbers from string in PHP.
1. PHP remove numbers from string using preg_replace() function
To remove numbers from string in PHP, you can use regular expression. Here’s an example of how to do this using ‘preg_replace()’. The preg_replace() function can simply remove numbers from a string by matching them with a regular expression. The preg_replace() function is a powerful tool in PHP that allows you to search for a pattern in a string and replace it with a specified value.
Here’s detailed explanation and examples for removing numbes from string using preg_replace().
Syntax:
preg_replace(pattern, replacement, subject);
- pattern: A regular expression that defined the characters or sequence you want to search for.
- replacement: The value that will replace the matched patterns.
- subject: The input string where the replacement will occur.
Example 1:
<?php
$old_string = "This is a testing pur333pose";
$newStringValue = preg_replace('/[0-9]+/', '', $old_string);
echo $newStringValue;
?>
Output:
This is a testing purpose
Explanation:
- ‘/[0-9]+/’ is the regular expression that matches all strings one or more digits (0-9).
- Replacing the matched digits with an empty (”) removes them from the string.
Example 2:
<?php
$old_string = "This is a testing pur333pose";
$newStringValue = preg_replace('/\d/', '', $old_string);
echo $newStringValue;
?>
Output:
This is a testing purpose
2. Remove numbers from a string with spaces
If you want to remove numbers but leave the string otherwise untouched. Use the same preg_replace() method.
Example:
<?php
$old_string = "This is a testing pur333pose";
$newStringValue = preg_replace('/\d+/', '', $old_string);
echo $newStringValue;
?>
Output:
This is a testing purpose
Explanation:
- ‘/\d+/’ is a shorthand for matching one or more digits, equivalent to ‘/[0-9]+/’.
- All the numbers are removed, but other characters like letters, spaces and panctuation remain.
I hope this tutorial help you.