How to Remove Numbers from String in PHP
Hello readers,
In this tutorial we will learn how can re remove numbers or digits from a given string. So let’s get started.
Method 1: In this method we will use PHP preg_replace() method. preg_replace() takes five parameters.
preg_replace(patterns, replacements, input, limit, count)
Parameter | Description |
---|---|
patterns (REQUIRED) | Takes a regular expression or array of regular expressions |
replacements (REQUIRED) | The replacement string or an array of replacement strings |
input (REQUIRED) | Actual string or array of strings in which replacements are being performed |
limit (OPTIONAL) | Defaults to -1, meaning unlimited. Sets a limit to how many replacements can be done in each string |
count (OPTIONAL) | After function execution, this variable will contain a number indicating how many replacements has occured |
<?php $my_string = "There are seven building 548 in this block.". $my_string_without_numbers = preg_replace('/[0-9]+/', '', $string); print($newString); ?> // OUTPUT There are seven building in this block.
Method 2: Using custom functions.
By this method we will create a custom function to replace all the numbertsd from a string.
<?php $string = "Hello 99 wor5875ld!"; function remove_numbers_from_string($string) { $num = array(0,1,2,3,4,5,6,7,8,9); return $new_string = str_replace($num, null, $string); } echo remove_numbers_from_string($string); ?> // OUTPUT Hello World!
Here you can see we have created a custom function called remove_numbers_from_string(). This custom function will take one parameter called “$string“. This is our given string which may have contain some number. After that, we have created an array ($num) which contains all the number digits. Then we are using PHP’s built in function str_replace() which is taking our two parameter $num array and given string. Finally we are passing our string and numbers array in this str_replace() method. This function will replace all the digits and output our string without all these digits.
That’s all for today. Thank you for your concentration. See you in next one.
If you like this article, please checkout our others article as well.
Laravel:
PHP:
Our YouTube Channel
See you in next one!