How to use chr() function in an array for cleaning strings from dangereous characters in PHP?

Hi everyone i was working on some php forms. I am a newbie so i might used a really annoying way to solve my problem. Here is my try:

<?php
function ascii(){
    $j = 0;
    for ($i = 33; $i < 65; $i++){
        // turn $i to ascii
        $k = chr($i);
        // put it in an array
        $text[$j] = $k;
        $j++;
    }      
    print_r($text);  
}
?>

Output for the ascii() :  Array ( [0] => ! [1] => " [2] => # [3] => $ [4] => % [5] => & [6] => ' 
[7] => ( [8] => ) [9] => * [10] => + [11] => , [12] => - 
[13] => . [14] => / [15] => 0 
[16] => 1 [17] => 2 [18] => 3 [19] => 4 
[20] => 5 [21] => 6 [22] => 7 [23] => 8 
[24] => 9 [25] => : [26] => ; [27] => < 
[28] => = [29] => > [30] => ? [31] => @ ) 

Even if it is a wrong way to collect wanted ascii characters in an array please just say it. Also i think i made a mistake with function and arrays but i couldn't solve it. What should i pass to function and return from it. If i use this function in something , should i pass the arguments by reference?

UPDATE

I have an output now. Time to improve function :). I am planning to use this array(after change something) with trim function in another loop. Is that a proper way to clean ASCII characters from a string?

2 answers

  • answered 2019-02-10 12:44 dWinder

    If you want to use chr I would recommend to change your function to:

    <?php
    function ascii(){
        for ($i = 33; $i < 65; $i++)
            $text[] = chr($i);
        return $text;
    }
    
    print_r(ascii());
    

    If you want to filter non-alphabetic char you may use ctype-alpha.

    If you had different propose for the asscii array please share you case clearly.

  • answered 2019-02-10 12:55 splash58

    I 'm not understood how you will use that array, but in any case you can fill it just by

    range('!', '@');