How to remove non-alphanumeric characters in PHP stirng?

Object Oriented ProgrammingPHPProgramming

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.

raja
Published on 26-Jun-2019 12:52:47
Advertisements