Tuesday, 23 January 2018

RGB2Hex

If you need to convert RGB-color into HEX-color, use this.

function rgb2hex($rgb){
   return sprintf("%06X", $rgb);
}
print rgb2hex(0x00FF00);
// returns --> 00FF00

print rgb2hex(65280);
// returns --> 00FF00

Ends with

Returns true or fales depending on whether the text ends with the given string or not.

/**
 * EndsWith
 * Tests whether a text ends with the given
 * string or not.
 *
 * @param     string
 * @param     string
 * @return    bool
 */
function EndsWith($Haystack, $Needle){
    // Recommended version, using strpos
    return strrpos($Haystack, $Needle) === strlen($Haystack)-strlen($Needle);
}

// Another way, using substr
function EndsWith_Old($Haystack, $Needle){
    return substr($Haystack, strlen($Needle)*-1) == $Needle;
}

$ExampleText = '[snippet]';

if (EndsWith($ExampleText, ']')){
    print 'The string ends with -> ] <-';
}


$ExampleText = 'Evil monkey';

if (!EndsWith($ExampleText, 'evil')){
    print 'The text does not start with evil!';
}

Remove duplicated lines

This function removes all duplicated lines of a text file. That's it.

/**
 * RemoveDuplicatedLines
 * This function removes all duplicated lines of the given text file.
 *
 * @param     string
 * @param     bool
 * @return    string
 */
function RemoveDuplicatedLines($Filepath, $IgnoreCase=false, $NewLine="\n"){

    if (!file_exists($Filepath)){
        $ErrorMsg  = 'RemoveDuplicatedLines error: ';
        $ErrorMsg .= 'The given file ' . $Filepath . ' does not exist!';
        die($ErrorMsg);
    }

    $Content = file_get_contents($Filepath);

    $Content = RemoveDuplicatedLinesByString($Content, $IgnoreCase, $NewLine);

    // Is the file writeable?
    if (!is_writeable($Filepath)){
        $ErrorMsg  = 'RemoveDuplicatedLines error: ';
        $ErrorMsg .= 'The given file ' . $Filepath . ' is not writeable!';   
        die($ErrorMsg);
    }

    // Write the new file
    $FileResource = fopen($Filepath, 'w+');     
    fwrite($FileResource, $Content);       
    fclose($FileResource); 
}


/**
 * RemoveDuplicatedLinesByString
 * This function removes all duplicated lines of the given string.
 *
 * @param     string
 * @param     bool
 * @return    string
 */
function RemoveDuplicatedLinesByString($Lines, $IgnoreCase=false, $NewLine="\n"){

    if (is_array($Lines))
        $Lines = implode($NewLine, $Lines);

    $Lines = explode($NewLine, $Lines);

    $LineArray = array();

    $Duplicates = 0;

    // Go trough all lines of the given file
    for ($Line=0; $Line < count($Lines); $Line++){

        // Trim whitespace for the current line
        $CurrentLine = trim($Lines[$Line]);

        // Skip empty lines
        if ($CurrentLine == '')
            continue;

        // Use the line contents as array key
        $LineKey = $CurrentLine;

        if ($IgnoreCase)
            $LineKey = strtolower($LineKey);

        // Check if the array key already exists,
        // if not add it otherwise increase the counter
        if (!isset($LineArray[$LineKey]))
            $LineArray[$LineKey] = $CurrentLine;       
        else               
            $Duplicates++;
    }

    // Sort the array
    asort($LineArray);

    // Return how many lines got removed
    return implode($NewLine, array_values($LineArray));   
}

// Example 1
// Removes all duplicated lines of the file definied in the first parameter.
$RemovedLinesCount = RemoveDuplicatedLines('test.txt');
print "Removed $RemovedLinesCount duplicate lines from the test.txt file.";

// Example 2 (Ignore case)
// Same as above, just ignores the line case.
RemoveDuplicatedLines('test.txt', true

Next related number

Returns the next higher or lower number in a given range.

// Returns the next higher or lower number
function NextRelatedNumber($number, $range){   
    $r = $number % $range;
    $f = $number - $r;
    $b = round($r / $range, 0);

    return ($b == 1) ? $f + $range : $f;   
}

// Returns the next higher number
function NextHigherNumber($number, $range){   
    $r = $number % $range;
    $f = $number - $r;
    $b = ceil($r / $range);

    return ($b == 1) ? $f + $range : $f;   
}

// Returns the next lower number
function NextLowerNumber($number, $range){   
    $r = $number % $range;
    $f = $number - $r;
    $b = floor($r / $range);

    return ($b == 1) ? $f + $range : $f;   
}

// Returns the next related number from an array
function NextNumberArray($Number, $NumberRangeArray){

    $w = 0;
    $c = -1;
    $abstand = 0;

    $l = count($NumberRangeArray);       
    for($pos=0; $pos < $l; $pos++){

        $n = $NumberRangeArray[$pos];

        $abstand = ($n < $Number) ? $Number - $n : $n - $Number;

        if ($c == -1){
            $c = $abstand;
            continue;
        }
        else if ($abstand < $c){
            $c = $abstand;
            $w = $pos;
        }
    }

    return $NumberRangeArray[$w];
}


// Examples
// --------

// 0 10 20 30 40 50 ...
print 'NextRelatedNumber: ';
print NextRelatedNumber(44, 10) . "\n";
// returns --> 40

// 0 20 40 60 80 100 ...
print 'NextHigherNumber: ';
print NextHigherNumber(41, 20) . "\n";
// returns --> 60

// 0 5 10 15 20 25 30 35 ...
print 'NextLowerNumber: ';
print NextLowerNumber(57, 5) . "\n";
// returns --> 55

// Example with Array
print 'NextNumberArray: ';
print NextNumberArray(45, array(3, 8, 19, 34, 56, 89)) . "\n";
// returns --> 34
// (45 is between 34 and 56 but 34 is the next)

Array change case

Saves the phpinfo() page to an file

function array_changecase($a, $c='l'){
    return array_change_key_case($a,($c=='u') ?
        CASE_UPPER : CASE_LOWER);
}
array_changecase(array("foO" => "bar", "noNe" => 1), 'u')<br/><br/>returns:<br/>array("FOO" => "bar", "NONE" => 1)

Restore array

Restores the array keys to 0,1,2,3,4,...

function restore_array($arr){
    if (!is_array($arr)){ return $arr; }
    $c = 0; $new = array();
    while (list($key, $value) = each($arr)){
        if (is_array($value)){
            $new[$c] = restore_array($value);
        }
        else { $new[$c] = $value; }
        $c++;
    }
    return $new;
}

restore_array(array('a' => 1, 'b' => 2)); --> returns array(0 => 1, 1 => 2)

URL functions

miscellaneous URL functions

// parse_url:

$url = "http://www.jonasjohn.de/post.php?example=yes&text=foobar";
$url = parse_url($url);

print_r($url);
/*
    will return this array:

    [scheme] => http
    [host] => www.jonasjohn.de
    [path] => /post.php
    [query] => example=yes&text=foobar
*/


// urldecode & urlencode:

$query = "example=yes&text=foo%28bar%29%2B";

print urldecode($query); // opposite: urlencode
// output: example=yes&text=foo(bar)+



// parse the query:

parse_str($query, $output);
print_r($output);

/*
    will return this array:

    [example] => yes
    [text] => foo(bar)+
*/