Showing posts with label preg_replace. Show all posts
Showing posts with label preg_replace. Show all posts

Monday, February 17, 2014

Removing special Characters from string


Here the following case how to remove special characters easily in a string using preg_replace.

function clean($string) {
   $string = str_replace('', '-', $string); // Replaces all spaces with hyphens.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

echo clean('a|"bc!@£de^&$f g');
Will output: abcdefg


Another example

$string = '<div>This..</div> <a>is<a/> <strong>hello</strong> <i>world</i> ! هذا هو مرحبا العالم! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text نص عربي test 123 و,.m,............ ~~~ ٍ،]ٍْ}~ِ]ٍ}"; ';
echo preg_replace('/[^A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));


Will output: This.. is hello world !    ! 
!@#$%^&&**(*)p.1@#$%^&^&*(()9089788675645645344234123131
 Arabic Text   test 123 .m............   

Friday, October 19, 2012

Remove special characters from file name

       If you use special characters filename

            $f_name = "filename"; // given filename

            $f_name = trim($f_name,".");  // trim the first or last character "."

            $afilename=explode(".",$f_name);  // explode filename using separator  "."

            $f_ext = end($afilename);  // end keyword used to return the array end of value

            $f_name = reset($afilename); //  reset keyword used to return the array start of value

            $filename = $f_name.".".$f_ext;

            $str    = $filename;

            $sp_chr = array("[,]","[']","[=]","[;]");

            $str = preg_replace($sp_chr,"-",$str);   // using preg replace to replace the . , = ;

            $str = preg_replace("/&/","and",$str);  // replace & to and





           // below steps are replace the . or * or ? or / <  > change to -.

            $str = str_replace(".","-",$str); 
            $str = str_replace(":","-",$str);
            $str = str_replace("*","-",$str);
            $str = str_replace("/","-",$str);
            $str = str_replace("<","-",$str);
            $str = str_replace(">","-",$str);
            $str = str_replace("\"","-",$str);

            $filename = $str;