removing bad characters

Discussion in 'PHP' started by k3str3l, May 17, 2007.

  1. #1
    Hi, I need to remove incorrect characters from a string.

    So lets say the string is 'T^^he Gold$£en R0"!ad'

    and i want to echo out 'The Golden Road'

    i have experimented with the trim function but could only remove the first bad character.
    :confused:
    Any ideas?

    thanks
     
    k3str3l, May 17, 2007 IP
  2. commandos

    commandos Notable Member

    Messages:
    3,648
    Likes Received:
    329
    Best Answers:
    0
    Trophy Points:
    280
    #2
    
    
    <?php
    
    $domain = "T^^he Gold$£en R0\"!ad";
    
    
    $toberemoved = array("^","/",":","$","*","&","@","%","(","{","£","!"); // add any char to be removed ...
    
    
    $domain = str_replace ($toberemoved,"" ,$domain);
    
    ?>
    
    PHP:
     
    commandos, May 17, 2007 IP
  3. k3str3l

    k3str3l Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The posted method almost works but not quite, is there a while loop method i could use to remove characters between certain ascii value range?
     
    k3str3l, May 17, 2007 IP
  4. commandos

    commandos Notable Member

    Messages:
    3,648
    Likes Received:
    329
    Best Answers:
    0
    Trophy Points:
    280
    #4
    you will have to use preg replace
     
    commandos, May 17, 2007 IP
  5. gfreeman

    gfreeman Peon

    Messages:
    40
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    What do you mean by almost but not quite?
    Rather than throw out characters within a "bad set", consider keeping only the characters within a "good set".
     
    gfreeman, May 17, 2007 IP
  6. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #6
    
    function alpha( $string )
    {
    	return preg_replace( '([^a-zA-Z ]+)', '', $string );	
    }
    echo alpha( 'T^^he Gold$£en Ro!ad' )
    
    PHP:
     
    krakjoe, May 17, 2007 IP
  7. gfreeman

    gfreeman Peon

    Messages:
    40
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Consider inserting 0-9 as well if you want to retain numbers too.
    Note the space after Z. It's important if you want to keep the spaces.
     
    gfreeman, May 17, 2007 IP