Search code examples
phphtmlspecialchars

Problems with str_split


I'm new here, and I have a question. I'm doing a code that I'll use soon, more something left me with a huge doubt. So I'm separating the word more special characters converted are being separated, I wish they would get together to assign a color to each then is there any way to do this?

Code:

<?php
$text = "My nickname is: &#1087;&euro;&#1071;d &Oslash;w&#1087;&euro;d"; #this would be the result of what i received via post
print_r(str_split($text));
?>

Result:

Array
(
    [0] => M
    [1] => y
    [2] =>  
    [3] => n
    [4] => i
    [5] => c
    [6] => k
    [7] => n
    [8] => a
    [9] => m
    [10] => e
    [11] =>  
    [12] => i
    [13] => s
    [14] => :
    [15] =>  
    [16] => &
    [17] => #
    [18] => 1
    [19] => 0
    [20] => 8
    [21] => 7
    [22] => ;
    [23] => &
    [24] => e
    [25] => u
    [26] => r
    [27] => o
    [28] => ;
    [...]
)

I'd like to return this:

Array (    [0] => M
    [1] => y
    [2] =>  
    [3] => n
    [4] => i
    [5] => c
    [6] => k
    [7] => n
    [8] => a
    [9] => m
    [10] => e
    [11] =>  
    [12] => i
    [13] => s
    [14] => :
    [15] =>  
    [16] => &#1087;
    [17] => &euro;
    [...]
)

Thank you for the help.

[UPDATED]

I tested the functions that friends have passed, most don't use utf-8 as my default charset ISO-8859-1, and one more thing I forgot to add, by editing the phrase "My nickname is:" and adding a & for example: "My nickname is & personal name" returns a bug. I appreciate who can help again.


Solution

  • Use preg_split():

    <?php
    $text = "My nickname is: &#1087;&euro;&#1071;d &Oslash;w&#1087;&euro;d"; #this would be the result of what i received via post
    print_r(preg_split('/(\&(?=[^;]*\s))|(\&[^;]*;)|/', $text, -1, PREG_SPLIT_DELIM_CAPTURE + PREG_SPLIT_NO_EMPTY));
    ?>