1

I have a javascript function which I wants in PHP, Here is my JavaScript function:

<script type="text/javascript">
                    str = '242357de5b105346ea2059795682443';
                    str_overral = str;
                    str_overral = str_overral.replace(/[^a-z0-9]/gi, '').toLowerCase();
                    str_res='';
                    for (i=0; i<str_overral.length; i++) {
                        l=str_overral.substr(i,1);
                        d=l.charCodeAt(0);
                        if ( Math.floor(d/2) == d/2 ) {
                            str_res+=l;
                        } else {
                            str_res=l+str_res;
                        }
                    }
                    document.write('<in');
                    document.write('put type="hidden" name="myInput" value="'+str_res+'" />');
                </script>

and above JavaScript function generates this string for myInput: 359795ae3515e753242db0462068244

And this I tried with PHP:

    $str = '242357de5b105346ea2059795682443';
    $str_overral = preg_replace('/[^a-z0-9]/i', '',$str);
    $str_overral = strtolower($str_overral);
    $str_res=''; 
    for ($i=0; $i<strlen($str_overral); $i++) {
        $l= substr($str_overral,$i,1);
        // PHP does not have charCodeAt() function so i used uniord()
        $d = uniord($l);
        if((floor($d)/2) == ($d/2))
            $str_res.=$l;
        else
            $str_res.= $l.$str_res;
    }
    echo $str_res;

function uniord($c) {
        $h = ord($c{0});
        if ($h <= 0x7F) {
            return $h;
        } else if ($h < 0xC2) {
            return false;
        } else if ($h <= 0xDF) {
            return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
        } else if ($h <= 0xEF) {
            return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6
                                     | (ord($c{2}) & 0x3F);
        } else if ($h <= 0xF4) {
            return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12
                                     | (ord($c{2}) & 0x3F) << 6
                                     | (ord($c{3}) & 0x3F);
        } else {
            return false;
        }
    }   

and above PHP code generates this string: 242357de5b105346ea2059795682443 so basically PHP just return $string as is.

As PHP does not have charCodeAt() function I found a solution here UTF-8 Safe Equivelant of ord or charCodeAt() in PHP , But that does not work for me, I even tried solution posted by 'hakre' in same thread.

Thank you for any kind of help.

UPDATE SOLUTION:

Here was fix:

if($d%2 == 0)
    $str_res.=$l;
else
    $str_res = $l.$str_res;
Community
  • 1
  • 1
user969068
  • 2,818
  • 5
  • 33
  • 64

1 Answers1

2
if((floor($d)/2) == ($d/2))

You have a ) in the wrong place. It should be after the first /2, not before it.

It could be made more efficient with if($d%2 == 0)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592