In this tutorial we will see How To Remove Numbers From String in PHP. PHP preg_replace() Function and PHP str_replace() Function can be used to remove all numbers from the given string.
Table of Contents
PHP str_replace() Function
PHP str_replace() Function replaces characters of string with other pre-defined characters.
PHP str_replace() Function can be used to remove all numbers from the string.
PHP str_replace() Function can work with both arrays and strings.
Take a look at the example below.
<?php
$string = "123HowTo821Code720School789";
$array = array(0,1,2,3,4,5,6,7,8,9);
$result = str_replace($array,'', $string);
echo $result;
?>
Output
HowToCodeSchool
In above example we have used str_replace() to remove all numbers from the string.
In this example we have used pre-defined array with all numbers inside, the str_replace() will look for all numbers from array in the main string and will replace them with '' or null or nothing.
This will remove all numbers from string.
Let's see a better way to do this.
PHP preg_replace() Function
PHP preg_replace() Function also performs the search and replace function. It can be used to remove the numbers from sting more effectively.
PHP preg_replace() Function work with a pattern or regular expression. You can use preg_replace() function for both arrays and strings.
Take a look at the code below.
<?php
$string = "123HowTo821Code720School789";
$result = preg_replace('/[0-9]+/', '', $string);
echo $result;
?>
Output
HowToCodeSchool
In above example PHP preg_replace() Function is used to look for numbers and then remove them from the string. /[0-9]+/ is a regular expression or a pattern that we have used to find numbers.
'' is null which is our replacement for each number present in a string.
Take a look at another example.
<?php
$string = "123HowTo821Code720School789";
$result = preg_replace('/\d+/', '', $string);
echo $result;
?>
This is also one way to remove numbers from string in php. /\d+/ is a pattern which also looks for number.