amb99 Posted February 2, 2007 Share Posted February 2, 2007 Hi, I am using this method to clean illegal chars from strings. $pattern = '/[^\w\.]/i'; $replacement = '_ILLEGAL_'; $clean = preg_replace($pattern, $replacement, $string); // note: $string would be the GET or POST of something Is there a way I can display the illegal chars that were removed? If I were to be able to do that, I could display precisely why the string was invalid, and would also be able to change $replacement to be _AT_ if illegal char was '@', or _SHARP_ if '#' and so on. Or is there already a snippet out there that can do this? Thank you for any help. Quote Link to comment Share on other sites More sharing options...
alpine Posted February 3, 2007 Share Posted February 3, 2007 Here is one, note that its php5 dependant due to str_split() <?php $string = "kfgak*suh@hd#t"; $invalid = array(); $filtered = array_values(str_replace(array_merge(range(a,z),range(A,Z),range(0,9),array('.')),'',str_split($string))); foreach(str_split($string) as $char){ if(in_array($char,$filtered,true)){ $invalid[] = $char; } } if(!empty($invalid)){ $string = str_replace(array("@","#"), array("_AT_","_SHARP_"), $string); $string = str_replace(array_values(str_replace(array_merge(range(a,z),range(A,Z),range(0,9),array('-','.','_')),'',str_split($string))),'_ILLEGAL_',$string); echo "<p>Following chars was not accepted:</p><ul><li>"; echo implode($invalid,'</li><li>'); echo "</li></ul>"; echo "String was translated to: $string"; } else{ echo "No illegal chars found"; } ?> This example prints out: Following chars was not accepted: * * * @ * # String was translated to: kfgak_ILLEGAL_suh_AT_hd_SHARP_t No regex though... Quote Link to comment Share on other sites More sharing options...
alpine Posted February 3, 2007 Share Posted February 3, 2007 I notice from a prev post that you are on php4, here is a str_split function to get my above example running under php4 <?php function str_split($string) { $piece = array(); $length = strlen($string); for($i=0;$i<$length;$i++) $piece[] = $string{$i}; return $piece; } ?> Quote Link to comment Share on other sites More sharing options...
amb99 Posted February 3, 2007 Author Share Posted February 3, 2007 Absolutely amazing. Thank you very much that worked. Tiny change: _- were illegal, I updated array('.') to array('-','.','_') for $filtered, it seems to be working Quote Link to comment Share on other sites More sharing options...
alpine Posted February 3, 2007 Share Posted February 3, 2007 Sorry - a glitch with the array, but you seem to grasp it and that's the point! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.