PHP Remove Numbers From String

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.

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.

How To Append a String in PHP How To Prepend a String in PHP Replace a Word In String in PHP Convert Special Characters To HTML Entities PHP Find Number of Words in a String in PHP How To Find String Length in PHP How To Convert String To Uppercase in PHP How To Convert String To Lowercase in PHP How to Combine Two Strings in PHP Delete Array Elements By Value in PHP Get First Element Of Array In PHP Remove Numbers From String in PHP Convert Timestamp To Date in PHP Convert a Date to Timestamp in PHP Get Current Page Slug in PHP Check If Session Is Started in PHP Split Sentence Into Words in PHP Remove Last Character From String in PHP PHP Remove Spaces From String Replace Space With Dash in PHP Remove Everything from String Except Numbers Using PHP Get Full Url Address Using PHP Automatic Copyright Year Using PHP Generate 4 Digit Random Number in PHP How To Check If a Number is Prime using PHP Convert Integer to String in PHP