Jump to content

[SOLVED] how to change @ to _AT_ and # to _SHARP_ etc


amb99

Recommended Posts

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.

Link to comment
Share on other sites

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...

Link to comment
Share on other sites

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;
}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.