Remove special characters from php string

Hello friends. At some point we need to filter our strings and remove some unwanted characters from the string for some purpose. It is quite easy to do this with regular expressions.

Php built-in function preg_replace() can be used to remove special characters from a string. It takes 3 parameters and its syntax is

$output = preg_replace(pattern, replacWith, string);

Remove all characters except alphabets and digits use this.


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

Remove all ascii characters from the string use this.


   $output=preg_replace('/[^(\x20-\x7f)]*/s','',$string);

Remove special characters from php string Remove special characters from php string Reviewed by JS Pixels on April 28, 2011 Rating: 5

13 comments:

  1. Great code....is there anyway to apply this, /[^a-zA-Z0-9]/s and keep spaces between the text? Otherwise "Today is a great day!!@@#$%#@@#!!!" becomes "Todayisagreatday"

    ReplyDelete
  2. You only have to give a space in your expression like
    /[^a-zA-Z0-9 ]/s
    and it will keep the space between text.
    Now "Today is a great day!!@@#$%#@@#!!!" becomes "Today is a great day"

    Thanks

    ReplyDelete
  3. Thnx man! Is there a way to replace the spaces between the strings to underscores?

    ReplyDelete
  4. Try this
    preg_replace("/\s/","_",html_entity_decode($s));

    IF you want to remove all adjacent spaces with another character visit

    This Post

    ReplyDelete
  5. it is working only for some specials chracters

    ReplyDelete
  6. my preg_replace code is
    $new_data = str_replace ("'", "", $data);
    $new_data = preg_replace ('/[^\p{L}\p{N}]/u', ' ', $new_data);

    its working fine but i want to change little bit in this code i want replace all special character with white space (space) but don't change ()brackets symbol
    how it is possible please help me

    ReplyDelete
  7. @ourseotool
    Try this

    $new_data = preg_replace('/[^a-z0-9\(\)]/si', ' ', $new_data);

    It will replace all special characters with whitespace except ( ) brackets.

    ReplyDelete


  8. output is "my name-------is--------yashwant"
    but i want this "my name-is-yashwant"
    is it possible

    ReplyDelete
    Replies
    1. @Yashwant Singh Gehlot

      Yes this is possible, try this

      preg_replace ('/-+/', '-', $str);

      Delete
  9. $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 (backslash) \ from this string

    anyone can help me ?

    ReplyDelete
    Replies
    1. Just use $str = str_replace("\", "", $str);

      Delete

Altaf Web. Powered by Blogger.