Saturday 26 May 2012

Remove Special Characters from a String using preg_replace in Php

Hi All, in my earlier post i have written about how to remove special characters from mysql database. Sometime we only want to get result of an input string as a simple composition of alphabets and numbers and we want to remove all special characters in the given string.
In this case Php provide an easy function to do the needful. We can remove all special characters by using preg_replace.
Here is the simple syntax for it.

$result  = preg_replace('/[^a-zA-z0-9/s','',$string);
where $string is the string in which we want to filter special characters and $result is the output string without any special characters.

We can also use another Php function str_replace() to achieve the same if we know what all we have to remove. Here is the simple syntax for it.
str_replace(mixed search,mixed replace,mixed subject[,int & replace_count]);

More information on www.narendrarathore.com

10 comments:

  1. Hi, it works but you forgot the ']' character ;)

    preg_replace('/[^a-zA-z0-9]/s','',$string);

    ReplyDelete
  2. Nice Written. An example of str_replace should have been given here.

    ReplyDelete
  3. Nice Written. An example of str_replace should have been given here.

    ReplyDelete
  4. Sarkari Jobs Board - is a job Portal in India to provides the information for the sarkari jobs, bank jobs, railway jobs, IT jobs, teaching jobs, defence jobs

    ReplyDelete
  5. preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $string);

    try this..

    ReplyDelete
    Replies
    1. thanks for your example Government Jobs. It's help me :)

      Delete
  6. can i use this pattern for it ../^'|[^A-Za-z0-9\'-]|'$/..its work but not escape hyphen.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. $str=SELECT P.*,C.name FROM `products` P left OUTER join categories C ON C.id = P.category_id WHERE P.subcategory_id =51 and P.status= 1 AND ( P.file_type=\'JPEG\' )ORDER BY id DESC limit 0,60


    now i want to remove \ from this string

    anyone can help me ?


    Note: ( P.file_type=\'JPEG\' ) \ is here

    ReplyDelete