How to remove non-alphanumeric characters in PHP stirng?


We can remove non-alphanumeric characters from the string with preg_replace() function in PHP. The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.

syntax

preg_replace(pattern,replacement,subject,limit,count )

Let's discuss the parameters of the function underneath.

pattern

This parameter contains the pattern to search for.

replacement

It is a mandatory parameter. This parameter may contain a string or an array with strings to replace.

subject

The string or an array with strings to search and replace.

limit

The maximum possible replacements for each pattern in each subject string

count

This is an optional parameter, if specified then this variable will be filled with the number of replacements done. 

Let's demonstrate with an example to remove non-alphanumeric characters from a string with the help of preg_replace() function.

Example

<?php
   $str = "tu!tor^ials$%!poi&nt";
   echo preg_replace('/[^a-zA-Z0-9]/','', $str);
?>

Output

tutorialspoint

Explanation

In the above example, a string "$str" contains non-alphanumeric characters. We have used preg_replace() used to extract those characters from the strings to get the desired output.

Updated on: 29-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements