Home  >  Q&A  >  body text

Remove the following characters ½ ´ ¤ £ € ¨ using php but without using preg_replace or str_replace functions

I have a problem that needs to be solved. I can't use preg_replace or str_replace because we can't predetermine the characters since the data comes from form input.

I am trying to remove these characters from this $name "Test ½ ´ ¤ £ € ¨" ##½ ´ ¤ £ € ¨

The same is true for the front end, the characters cannot be predetermined

I tried the following methods but none of them worked

$name = "Test ½ ´ ¤ £ € ¨";

mb_convert_encoding(strval($name);

utf8_decode(strval($name);

My ideal output is

Test

P粉163465905P粉163465905426 days ago522

reply all(1)I'll reply

  • P粉731861241

    P粉7318612412023-09-13 15:38:26

    You can always iterate over the characters in a string. But be careful: PHP does not support Unicode natively.

    $remove = array( '½', '´', '¤', '£', '€' );
    $result = '';
    $name = "Test ½ ´ ¤ £ € ¨";
    
    $count = mb_strlen($name, 'UTF-8');
    for( $i = 0; $i < $count; $i++ ){
        $char = mb_substr( $name, $i, 1, 'UTF-8' );
        if( ! in_array( $char, $remove ) {
          $result .= $char;
        }
    }
    

    This iterates over the multibyte characters in the user-supplied string and allows you to perform any operation on them. The example builds a resulting string, omitting the characters you mentioned. (Not debugged, sorry.)

    (IMHO, I think your reasons for avoiding string replacement functions are probably wrong. The benefit of using regex character classes is this: regex authors have solved a lot of weird edge cases where Unicode contains many disturbing situations.)

    reply
    0
  • Cancelreply