How to move all special characters to the beginning of a string in PHP

2 Answers

0 votes
function move_special_characters_to_beginning($s) { 
    $len = strlen($s); 
    $chars = "";
    $pecial_characters = ""; 
          
    for ($i = 0; $i < $len; $i++) { 
         $ch = $s[$i]; 
         if (ctype_alnum($ch)) {
            $chars = $chars . $ch; 
         }
         else {
            $pecial_characters = $pecial_characters . $ch; 
         }
    } 

    return $pecial_characters . $chars; 
} 
  

$s = "c++14@vb.net&%java*() php <>/python 3.7.3"; 

echo move_special_characters_to_beginning($s);
     

 
   
/*
run:
        
++@.&%*() <>/ ..c14vbnetjavaphppython373
 
*/

 



answered Aug 15, 2019 by avibootz
edited Dec 13, 2025 by avibootz
0 votes
unction moveSpecialCharactersToBeginning(string $s): string {
    $specials = "";
    $chars = "";

    // Iterate through each character
    for ($i = 0; $i < strlen($s); $i++) {
        $ch = $s[$i];
        if (ctype_alnum($ch) || ctype_space($ch)) {
            $chars .= $ch;
        } else {
            $specials .= $ch;
        }
    }

    return $specials . $chars;
}

$s = "c++20@c&^java*(rust) php <>/python 3.14.2";

echo moveSpecialCharactersToBeginning($s);



/*
run:

++@&^*()<>/..c20cjavarust php python 3142

*/

 



answered Dec 13, 2025 by avibootz

Related questions

...