reijin
reijin

Reputation: 121

strpos() returns wrong position

I'm new to PHP, but I thought I'd give it a try...

Here is my code:

function ScrambleDataPlus($inData){
    $normalAlphabet =   "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜabcdefghijklmnopqrstuvwxyzäöü.-,& ";
    $scrambAlphabet1 =  "ZXe.LSzdQVkcOt74Üüsry12b$0B#RfWöiEw,aIPAKDC3ÄN&JTjFmgn6Ux8YpvoqhGu5älHÖ9M";
    $scrambAlphabet2 =  "1eTLUÄzXjYp.dx684IÜ5äWgnCüsr7DEw,3voFGVhiQu&HÖ2JfOty#RbMP9ZamklSö$0BNcqAK";
    $reorderPosition =  array(3,12,15,7,2,11,14,1,10,8,4,13,6,16,5,9,0);

    $outData = array();
    $backup = array();
    $result = "";
    $alphabetPosition = 0;
    $newPosition = 0;

    if(strlen($inData) == 17)
    {
        //Scramble data with first aphabet
        for ($i = 0; $i < strlen($inData); $i += 2)
        {
            $alphabetPosition = strpos($normalAlphabet, $inData[$i]);               
            $outData[$i] = $scrambAlphabet1[$alphabetPosition];
            //print("From: ".$inData[$i]." to: ".$outData[$i]);
        }
        //print(sizeof($outData)."<br>");
        //printArray($outData);

        //Scramble data with second aphabet
        for ($i = 1; $i < strlen($inData); $i += 2)
        {
            $alphabetPosition = strpos($normalAlphabet, $inData[$i]);
            $outData[$i] = $scrambAlphabet2[$alphabetPosition];

        }
        //print(sizeof($outData)."<br>");
        //printArray($outData);

        //mix original order
        $backup = $outData;
        for ($i = 0; $i < strlen($inData); $i++)
        {
            $newPosition = $reorderPosition[$i];
            $outData[$i] = $backup[$newPosition];

        }
        //print(sizeof($outData)."<br>");
        //printArray($outData);

        for ($i = 0; $i < sizeof($outData); $i++)
        {
            $result .= $outData[$i];
            //print($i.". iteration: ".$outData[$i]."<br>");
        }
    }
    else
        $result = "Fehler";


    return $result;
}

The two strings are my scrambling alphabets. I noticed some strange behaviour: Some letters are getting replaced by wrong "scrambled" letters.

e.g: From: 0 to: Z; From: . to: H; From: 7 to: d; From: 2 to: e; From: 1 to: X; From: h to: N; From: l to: j; From: o to: g; From: 0 to: Z; 9

notice, that "." should be "l" (one) and "l" (lower L) should be "F" - so what is going on here?!

PS.: sry for that debug stuff - I just wanted to know what is going on...

Upvotes: 0

Views: 964

Answers (2)

reijin
reijin

Reputation: 121

Needed to set the encoding to UTF-8 and use mb_strpos instead of strpos:

mb_internal_encoding("UTF-8");

Upvotes: 0

Lusitanian
Lusitanian

Reputation: 11122

Try the multibyte string functions with mb_strpos(). It looks like you have some non-Latin characters, and PHP's default string library isn't compatible with anything but ISO-8859-1

Upvotes: 8

Related Questions