PHP - iterate on string characters

前端 未结 9 852
失恋的感觉
失恋的感觉 2020-12-04 14:01

Is there a nice way to iterate on the characters of a string? I\'d like to be able to do foreach, array_map, array_walk, array_

相关标签:
9条回答
  • 2020-12-04 14:39

    Iterate string:

    for ($i = 0; $i < strlen($str); $i++){
        echo $str[$i];
    }
    
    0 讨论(0)
  • 2020-12-04 14:39

    If your strings are in Unicode you should use preg_split with /u modifier

    From comments in php documentation:

    function mb_str_split( $string ) { 
        # Split at all position not after the start: ^ 
        # and not before the end: $ 
        return preg_split('/(?<!^)(?!$)/u', $string ); 
    } 
    
    0 讨论(0)
  • 2020-12-04 14:40

    Step 1: convert the string to an array using the str_split function

    $array = str_split($your_string);

    Step 2: loop through the newly created array

    foreach ($array as $char) {
     echo $char;
    }
    

    You can check the PHP docs for more information: str_split

    0 讨论(0)
提交回复
热议问题