Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2011
    Posts
    428
    Thanks
    18
    Thanked 26 Times in 26 Posts

    Question Translating JavaScript to PHP

    I have a few bits of code that are in JavaScript that I need converted to PHP and I'm having a heck of a time doing so. I'll post both the JavaScript and the PHP that I attempted to make out of it and I'm looking for opinions on what's right and wrong, or what could be improved.


    Code:
    function func_1(t) {
        return t.replace(/(<([^>]+)>)/gi,"")
    }
    function func_2(t) {
        if(t != '' && t != '{pass}') {
            var c = t.substr(0, 1);
            while(c == ' ') {
                t = t.substr(1);
                c = t.substr(0, 1)
            }
            t = c.toUpperCase() + t.substr(1);
            var c = t.substr(t.length - 1);
            while(c == ' ') {
                t = t.substr(0, t.length - 1);
                c = t.substr(t.length - 1)
            }
            if(c != '.' && c != '?' && c != '!')
                t += '.'
        }
        return func_1(t.replace(/(`\u2018|\u2019|\u201A|\u201B|\u201C|\u201D|\u201E|\u201F)/g, "'").replace(/(~\u00AC|\u2010|\u2011|\u2012|\u2013|\u2014|\u2015)/g, "-")).replace(/@/g, '')
    }
    function func_3(v) {
        var c = "";
        var e = "";
        v = v.replace(/[|]/g, "{*}");
        for(var i = 0; i <= v.length; i++) {
            if(v.charCodeAt(i) > 255) {
                e = escape(v.charAt(i));
                if(e.substring(0, 2)=="%u") {
                    c += "|" + e.substring(2, e.length)
                }else{
                    c += e
                }
            }else{
                c += v.charAt(i)
            }
        }
        c = c.replace('|201C', "'").replace('|201D', "'").replace('|2018', "'").replace('|2019', "'").replace('`', "'").replace('%B4', "'").replace('|FF20', "").replace('|FE6B', "");
        return c
    }
    function func_4(v) {
        return unescape(v.replace(/%/g, '{--}').replace(/[|]/g, "%u")).replace(/{\*}/g, "|").replace(/\%u/g, "|").replace(/{--}/g, '%')
    }
    PHP Code:
    function func_1($t)
    {
        return 
    preg_replace("/(\<([^\>]+)\>)/"""$t); //Not sure on what needed escaped here
    }
    function 
    func_2($t)
    {
        if(
    $t != '' && $t != '{pass}')
        {
            
    $t ucfirst(trim($t));
            
    $c substr($t, -1);
            
    $t substr($t0, -1);
            if(
    $c != '.' && $c != '?' && $c != '!')
                
    $t .= '.';
        }
        
    $t preg_replace("/(\`\‘|\’|\‚|\‛|\“|\”|\„|\‟)/""'"$t); //I converted all of these online and got this result, the format used above is preferred if possible
        
    $t preg_replace("/(\~\¬|\‐|\‑|\‒|\–|\—|\―)/""-"$t);
        
    $t preg_replace("/@/"""$t);
        return 
    func_1($t);
    }
    function 
    func_3($v)
    {
        
    $c "";
        
    $e "";
        
    $v preg_replace("/\[\|\]/""{*}"$v);
        for(
    $i 0$i <= strlen($v); i++)
        {
            if(
    charCodeAt($vi) > 255)
            {
                
    $e rawurlencode($v{$i});
                if(
    substr($e02) == "%u")
                    
    $c .= "|".substr($e2);
                else
                    
    $c .= $e;
            }
            else
                
    $c .= $v{$i};
        }
        
    $c preg_repalce("/\|201C/""'"$c);
        
    $c preg_repalce("/\|201D/""'"$c);
        
    $c preg_repalce("/\|2018/""'"$c);
        
    $c preg_repalce("/\|2019/""'"$c);
        
    $c preg_repalce("/\`/""'"$c);
        
    $c preg_repalce("/\%B4/""'"$c);
        
    $c preg_repalce("/\|FF20/"""$c);
        
    $c preg_repalce("/FE6B/"""$c);
        return 
    $c;
    }
    function 
    func_4($v)
    {
        
    $v preg_repalce("/\%/""{--}"$v);
        
    $v preg_repalce("/\[\|\]/""%u"$v);
        
    $v preg_repalce("/\{\*\}/""|"$v);
        
    $v preg_repalce("/\%u/""|"$v);
        
    $v preg_repalce("/\{\-\-\}/""%"$v);
        return 
    rawurldecode($v);

    A lot of my issue deals with the regex replacements and the fact that the JavaScript uses UTF-8 while PHP does not. I need a fix of some sort to help solve this.

    If there are any other functions I call with the php and aren't listed then they're probably from my basic functions file that I built, which has a bunch of functions I feel are necessary (or at least handy) to have.

    PHP Code:
    <?php
    ##########################
    #### Created By: Dubz ####
    ##########################

      ########################
    #### This file contains ####
    ####  a few basic php   ####
    ####     functions      ####
      ########################

    //Define BASICFUNCTIONS so users can add a check for this file and avoid calling it twice
    define("BASICFUNCTIONS"true);

    /*
    * @credit Dubz
    *
    * Converts error numbrs to the string used to define them
    *
    * @param $errno The error number provided
    * @return A string that is used to define the error number
    */
    function errtostr($errno)
    {
        switch(
    $errno)
        {
            case 
    E_ERROR: return 'E_ERROR'; break;                            #1
            
    case E_WARNING: return 'E_WARNING'; break;                        #2
            
    case E_PARSE: return 'E_PARSE'; break;                            #4
            
    case E_NOTICE: return 'E_NOTICE'; break;                        #8
            
    case E_CORE_ERROR: return 'E_CORE_ERROR'; break;                #16
            
    case E_CORE_WARNING: return 'E_CORE_WARNING'; break;            #32
            
    case E_COMPILE_ERROR: return 'E_COMPILE_ERROR'; break;            #64
            
    case E_COMPILE_WARNING: return 'E_COMPILE_WARNING'; break;        #128
            
    case E_USER_ERROR: return 'E_USER_ERROR'; break;                #256
            
    case E_USER_WARNING: return 'E_USER_WARNING'; break;            #512
            
    case E_USER_NOTICE: return 'E_USER_NOTICE'; break;                #1024
            
    case E_STRICT: return 'E_STRICT'; break;                        #2048
            
    case E_RECOVERABLE_ERROR: return 'E_RECOVERABLE_ERROR'; break;    #4096
            
    case E_DEPRECATED: return 'E_DEPRECATED'; break;                #8192
            
    case E_USER_DEPRECATED: return 'E_USER_DEPRECATED'; break;        #16384
            
    case E_ALL: return 'E_ALL'; break;                                #32767
            
    default:
                return 
    false;
        }
    }


    /*
    * @Credit Dubz
    *
    * Tells if a number is within the given range
    *
    * @param $num The number to check
    * @param $low The lower number of the range
    * @param $high The higher number of the range
    * @return A boolen telling if the number is in the range
    */
    function in_range($num$low$high)
    {
        return ((
    $num >= $low) && ($num <= $high));
    }


    /*
    * @Credit Fou-Lu
    * @Credit Dubz
    *
    * Grabs all of the tag attribue values of the html code given
    *
    * @param $html The code of an html file
    * @param $tag The name of the tags to collect
    * @return An array of the names and values of the tags
    */
    function get_tag_data($html$tag)
    {
        
    $dom = new DOMDocument('1.0');
        
    $dom->loadHTML($html);
        
    $aResult = array();
        if(
    $input $dom->getElementsByTagName($tag))
        {
            foreach(
    $input as $item)
            {
                
    $attributes $item->attributes;
                if(
    $attributes->getNamedItem('name') != null)
                {
                    
    $aResult[$attributes->getNamedItem('name')->nodeValue] = array();
                    foreach(
    $attributes as $attr)
                    {
                        
    $aResult[$attributes->getNamedItem('name')->nodeValue][$attr->name] = $attr->value;
                    }
                }
            }
        }
        return 
    $aResult;
    }


    /*
    * @Credit Dubz
    *
    * Returns the extension of a given filename
    *
    * @param $filename The name of the file
    * @return A string of the extension
    */
    function getFileExtension($filename)
    {
        
    #Remove any extra queries if from a url (won't affect normal queries)
        
    $filename preg_replace('/^(.*)\?/''$1'$filename);
        
    $parts explode("."$filename);
        
    $ext array_pop($parts);
        return 
    $ext;
    }


    /*
    * @Credit Dubz
    *
    * Encodes a string to hex
    *
    * @param $str The string to encode
    * @return A hex encoded version of the string
    */
    function strtohex($str)
    {
        
    $hex '';
        for(
    $i 0$i strlen($str); $i++)
            
    $hex .= '%'.bin2hex($str{$i});
        return 
    $hex;
    }


    /*
    * @Credit Dubz
    *
    * Decodes a hex string
    *
    * @param $hex The string to decode
    * @return A decoded version of the hex string
    */
    function hextostr($hex)
    {
        
    $str pack("H*"str_replace('%'''$hex));
        return 
    $str;
    }


    /*
    * @Credit [Unknown]
    *
    * Properly adjusts the case for a person's name
    *
    * @param $string The string to capitalize
    * @return A properly capitalized string for names
    */
    function ucname($string)
    {
        
    $string ucwords(strtolower($string));
        foreach (array(
    '-''\'') as $delimiter)
        {
            if (
    strpos($string$delimiter) !== false)
                
    $string implode($delimiterarray_map('ucfirst'explode($delimiter$string)));
        }
        return 
    $string;
    }


    /*
    * @Credit [Unknown]
    *
    * The equivelant to javascript's charCodeAt() function
    *
    * @param $str The input string
    * @param $index The position in the string
    * @return 
    */
    function charCodeAt($str$index)
    {
        
    $char mb_substr($str$index1'UTF-8');
        if(
    mb_check_encoding($char'UTF-8'))
        {
            
    $ret mb_convert_encoding($char'UTF-32BE''UTF-8');
            return 
    hexdec(bin2hex($ret));
        }
        return 
    null;
        return 
    utf8_ord(utf8_charAt($str$index));
    }


    /*
    *
    * @Credit [Unknown]
    *
    * utf8 supported ord function
    *
    * @param $char The input character
    * @return A numeric representation of the ord
    */
    function utf8_ord($char)
    {
        
    $len strlen($char);
        if(
    $len <= 0)
            return 
    false;
        
    $h ord($char{0});
        if (
    $h <= 0x7F)
            return 
    $h;
        if (
    $h 0xC2)    
            return 
    false;
        if (
    $h <= 0xDF && $len>1)
            return (
    $h 0x1F) <<  | (ord($char{1}) & 0x3F);
        if (
    $h <= 0xEF && $len>2)
            return (
    $h 0x0F) << 12 | (ord($char{1}) & 0x3F) << | (ord($char{2}) & 0x3F);          
        if (
    $h <= 0xF4 && $len>3)
            return (
    $h 0x0F) << 18 | (ord($char{1}) & 0x3F) << 12 | (ord($char{2}) & 0x3F) << | (ord($char{3}) & 0x3F);
        return 
    false;
    }


    /*
    *
    * @Credit [unknown]
    *
    * utf-8 supported character selection
    *
    * @param $str The input string
    * @param $num The position of the character
    * @return The character at the given position
    */
    function utf8_charAt($str$num)
    {
        return 
    mb_substr($str$num1'UTF-8');
    }


    /*
    *
    * @Credit Rizal Almashoor
    *
    * Performs a 32 bit left shift on 64 bit machines
    *
    * @param $a Input number
    * @param $b Number of steps
    * @Return a number that has been shifted left
    */
    function bitShiftLeft_32($a$b)
    {
        
    // convert to binary (string)
        
    $binary decbin($a);
        
    // left-pad with 0's if necessary
        
    $binary str_pad($binary64'0'STR_PAD_LEFT);
        
    // left shift manually
        
    $binary .= str_repeat("0"$b);
        
    // get the last 32 bits
        
    $binary substr($binary, -32);
        
    // if it's a negative number return the 2's complement
        // otherwise just return the number
        
    if ($binary{0} == "1")
        {
            return -(
    pow(231) - bindec(substr($binary1)));
        }
        else
        {
            return 
    bindec($binary);
        }
    }


    /*
    *
    * @Credit Dubz
    *
    * Performs a 32 bit right shift on 64 bit machines
    *
    * @param $a Input number
    * @param $b Number of steps
    * @Return a number that has been shifted right
    */
    function bitShiftRight_32($a$b$leadingZeros false)
    {
        
    $strip 32;
        
    $strip -= $b;
        
    // convert to binary (string)
        
    $binary decbin($a);
        
    // Pad with 0's for 64-bit
        
    $binary str_pad($binary64'0'STR_PAD_LEFT);
        
    // Strip the numbers to 32-bit and those being shifted
        
    $binary substr($binary32$strip);
        
    // Pad with the first digit to 32-bit
        
    $binary str_pad($binary32$leadingZeros $binary{0}, STR_PAD_LEFT);
        
    // if it's a negative number return the 2's complement
        // otherwise just return the number
        
    if ($binary{0} == "1")
        {
            return -(
    pow(231) - bindec(substr($binary1)));
        }
        else
        {
            return 
    bindec($binary);
        }
    }

    /*
    *
    * @Credit Dubz
    *
    * Performs a 32 bit invert on 64 bit machines
    *
    * @param $a Input number
    * @Return an inverted version of the number
    */
    function bitInvert_32($a)
    {
        
    $inverted = -1;
        
    $inverted -= $a;
        return 
    $inverted;
    }


    /*
    *
    * @Credit voromax
    *
    * Return unicode char by its code
    *
    * @param $u Input number
    * @return The character
    */
    function unichr($a)
    {
        return 
    mb_convert_encoding('&#'.intval($a).';''UTF-8''HTML-ENTITIES');
    }


    /*
    *
    * @Credit Dubz
    *
    * Return mime type of file extension
    *
    * @param $extension Extension of file (without the period)
    * @return A string of the mime type
    */
    function getMimeType($extension)
    {
        switch(
    $extension)
        {
            
    #Applications
            
    case '7z':
                return 
    'application/x-7z-compressed';
            break;
            case 
    'swf':
                return 
    'application/x-shockwave-flash';
            break;
            case 
    'woff':
                return 
    'application/octet-stream';
            break;
            case 
    'zip':
                return 
    'application/zip';
            break;
            
    #Images
            
    case 'bmp':
                return 
    'image/bmp';
            break;
            case 
    'ico':
                return 
    'image/ico';
            break;
            case 
    'gif':
                return 
    'image/gif';
            break;
            case 
    'jpg':
            case 
    'jpeg':
                return 
    'image/jpeg';
            break;
            case 
    'png':
                return 
    'image/png';
            break;
            case 
    'tiff':
                return 
    'image/tiff';
            break;
            
    #Text
            
    case 'css':
                return 
    'text/css';
            break;
            case 
    'js':
                return 
    'text/javascript';
            break;
            case 
    'html':
                return 
    'text/html';
            break;
            default:
                return 
    'text/plain';
        }
    }


    /*
    *
    * @Credit Dubz
    *
    * Replace words in a string with strings matching the regex with a given array or set constants
    *
    * @param $data A string (or array of strings) to replace
    * @param $replacement An array of variables to use instead of constants
    * @param $pattern The regex pattern to search for using $1 as the word filler (default is between brackets {$1})
    * @return A string of the mime type
    */
    function replace($data$replacement null$pattern '/\{$1\}/')
    {
        
    #Make sure the variable is in the pattern, else append it
        
    if(strpos($pattern'$1') === false)
            
    $pattern .= '$1';
        
    #Are we doing this with an array? If so, handle it with recursion and return it
        
    if(is_array($data))
        {
            foreach(
    $data as $k => $v)
                
    $data[$k] = replace($v$replacement$pattern);
            return 
    $data;
        }
        
    #Find the constants by the pattern
        
    if(is_null($replacement))
        {
            
    preg_match_all(preg_replace('/\$1/''([a-zA-Z\_]{1}\w*)'$pattern), $data$matches);
            
    #Remove duplicates in the array
            
    $matches array_unique($matches[1]);
            
    #Loop through the pattern and replace any matches that are defined as constants
            
    foreach($matches as $match)
            {
                if(
    defined($match))
                    
    $data preg_replace(preg_replace('/\$1/'$match$pattern), constant($match), $data);
            }
        }
        
    #Use the array of replacement data to replace
        
    else
        {
            foreach(
    $replacement as $key => $value)
                if(!
    is_array($value))
                    
    $data preg_replace(preg_replace('/\$1/'$key$pattern), $value$data);
        }
        
    #Return the data
        
    return $data;
    }


    /*
    *
    * @Credit xdazz
    *
    * Convert a Unicode number into a character
    *
    * This function simulates JavaScripts version of string.fromCharCode()
    *
    * @return A string of the characters combined
    */
    function str_fromCharCode()
    {
        return 
    implode(array_map('chr'func_get_args()));
    }
    ?>
    I had to cut part if the basic functions out due to the post length limit but it should have the needed functions.


    This seems to be the only part I'm having troubles with, the other parts I believe are finished.

  • #2
    Regular Coder
    Join Date
    Sep 2011
    Posts
    428
    Thanks
    18
    Thanked 26 Times in 26 Posts
    Also, keep in mind that I don't know JavaScript well enough to know what should and shouldn't be escaped, or what is and isn't a regular expression in the replace. I know PHP very well and I know regular expressions (on a basic level), but it's hard to translate it from a language you barely know.

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    JavaScript:

    \u2018|\u2019|\u201A|\u201B|\u201C|\u201D|\u201E|\u201F

    PHP equivalent:

    \x{2018}|\x{2019}|\x{201A}|\x{201B}|\x{201C}|\x{201D}|\x{201E)|\x{201F}
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •