Pergunta

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.

Foi útil?

Solução 2

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));
?>

Outras dicas

You can try to write your own str_split, which could look like the following

function str_split_encodedTogether($text) {
    $result = array();
    $length = strlen($text);
    $tmp = "";
    for ($charAt=0; $charAt < $length; $charAt++) {
        if ($text[ $charAt ] == '&') {//beginning of special char
            $tmp = '&';
        } elseif ($text[ $charAt ] == ';') {//end of special char
            array_push($result, $tmp.';');
            $tmp = "";
        } elseif (!empty($tmp)) {//in midst of special char
            $tmp .= $text[ $charAt ];
        } else {//regular char
            array_push($result, $text[ $charAt ]);
        }
    }
    return $result;
}

Basically what it does is check if the current character is a &, if so, save all following characters (including ampersand) in $tmp until ;. This basically gives you the wanted result but will fail, whenever there is a & which doesn't belong to an encoded character.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top