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
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
Reviewed by JS Pixels
on
April 28, 2011
Rating:
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"
ReplyDeleteYou only have to give a space in your expression like
ReplyDelete/[^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
Nice code..
ReplyDeleteThnx man! Is there a way to replace the spaces between the strings to underscores?
ReplyDeleteTry this
ReplyDeletepreg_replace("/\s/","_",html_entity_decode($s));
IF you want to remove all adjacent spaces with another character visit
This Post
it is working only for some specials chracters
ReplyDeletemy preg_replace code is
ReplyDelete$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
@ourseotool
ReplyDeleteTry this
$new_data = preg_replace('/[^a-z0-9\(\)]/si', ' ', $new_data);
It will replace all special characters with whitespace except ( ) brackets.
not got any idea
ReplyDelete
ReplyDeleteoutput is "my name-------is--------yashwant"
but i want this "my name-is-yashwant"
is it possible
@Yashwant Singh Gehlot
DeleteYes this is possible, try this
preg_replace ('/-+/', '-', $str);
$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
ReplyDeletenow i want to remove (backslash) \ from this string
anyone can help me ?
Just use $str = str_replace("\", "", $str);
Delete