Php Flow » Php

PHP: Remove Special Character From String

In this tutorial I will discuss how to remove special character from string in PHP. Sometimes we need to get result of an input string as a simple composition of alphabets and numbers and we want to remove all special characters by using preg_replace.

Here is the simple syntax:

$result = preg_replace($pattern, $replaceWith , $string);
$result = This is the output string without special characters.
$string = This is the string which you want filter special characters.


Code:

1
2
3
4
5
6
7
8
9
function RemoveSpecialChar($value){
$result  = preg_replace('/[^a-zA-Z0-9_ -]/s','',$value);

return $result;
}
How to Call method:

echo $obj->RemoveSpecialChar(“does’t happened ‘ ‘ test”);
Result:
does t happened test

You can also use another PHP function str_replace() to get the same result as above script, if we know what all we have to remove special characters.

The syntax is:

$title = str_replace( array( ‘\”, ‘”‘, ‘,’ , ‘;’, ‘<', '>‘ ), ‘ ‘, $value);

Example:

Code
function RemoveSpecialChar($value){
$title = str_replace( array( ‘\”, ‘”‘, ‘,’ , ‘;’, ‘<', '>‘ ), ‘ ‘, $value);

return $title;
}

How to call Method
echo $obj->RemoveSpecialChar(“does’t happened ‘ ‘ test”);

Result:
does t happened test

Did you enjoy this article? Share it!

About the Author:

Hi, This is Parvez Alam from India. I am software developer with 4 years’ experience in web development. I have submitted articles on PHP, Mysql, Magento,CSS, HTML, jQuery, web designing and social API. You can subscribe to my blog via RSS/Twitter/Google plus and Facebook.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>