PHP
downloads | documentation | faq | getting help | mailing lists | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

trim> <substr_replace
Last updated: Fri, 14 Nov 2008

view this page in

substr

(PHP 4, PHP 5)

substr文字列の一部分を返す

説明

string substr ( string $string , int $start [, int $length ] )

文字列 string の、start で指定された位置から length バイト分の文字列を返します。

パラメータ

string

入力文字列。

start

start が正の場合、返される文字列は、 string の 0 から数えて start 番目から始まる文字列となります。 例えば、文字列'abcdef'において位置 0にある文字は、'a'であり、 位置2には'c'があります。

start が負の場合、返される文字列は、 string の後ろから数えて start 番目から始まる文字列となります。

例1 負の start の使用

<?php
$rest 
substr("abcdef", -1);    // "f" を返す
$rest substr("abcdef", -2);    // "ef" を返す
$rest substr("abcdef", -31); // "d" を返す
?>

length

length が指定され、かつ正である場合、 返される文字列は start (string の長さに依存します) から数えてlength 文字数分となります。 もし stringstart の文字列長より小さいもしくは等しい場合、FALSE が返されます。

length が指定され、かつ負である場合、 string の終端から多くの文字が省略されます (start が負の場合、 開始位置は文字列の終端を過ぎているので) 。 もし start が切り出し位置を超える場合、 空文字が返されます。

例2 負の length の使用

<?php
$rest 
substr("abcdef"0, -1);  // "abcde" を返す
$rest substr("abcdef"2, -1);  // "cde" を返す
$rest substr("abcdef"4, -4);  // "" を返す
$rest substr("abcdef", -3, -1); // "de" を返す
?>

返り値

文字列の一部を返します。

例3 基本的な substr() の使用法

<?php
echo substr('abcdef'1);     // bcdef
echo substr('abcdef'13);  // bcd
echo substr('abcdef'04);  // abcd
echo substr('abcdef'08);  // abcdef
echo substr('abcdef', -11); // f

// 文字列中の 1 文字にアクセスすることも
// "角括弧" を使用することで可能
$string 'abcdef';
echo 
$string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>



trim> <substr_replace
Last updated: Fri, 14 Nov 2008
 
add a note add a note User Contributed Notes
substr
wrapbit at yahoo dot com
31-Oct-2008 02:00
<?php
$cfg
[csvEnc] = '"';
$cfg[csvEsc] = '\\';
$cfg[csvTerm] = ",";

if( !
function_exists("parse_csv_aux") ){
    function
parse_csv_aux( $string ){
        global
$cfg;
       
$product = "";
       
$in_quote = FALSE;
       
$skipped_quote = FALSE;
        for(
$i = 0 ; $i < strlen($string) ; $i++){
            if(
$string{$i} == $cfg[csvEnc] ){
                if(
$in_quote){
                    if(
$skipped_quote){
                       
$product .= $cfg[csvEnc];
                       
$skipped_quote = FALSE;
                    }
                    else if( !
$skipped_quote ){
                       
$skipped_quote = TRUE;
                    }
                   
$in_quote = FALSE;
                }
                else{
                    if(
$skipped_quote) $skipped_quote = FALSE;
                   
$in_quote = TRUE;
                }
            }
            else if(
$string{$i} == "," ){
                if(
$in_quote){
                   
$product .= ",";
                }
                else{
                   
$product .= " ~ ";
                }
            }
            else{
                if(
$in_quote){
                   
//$in_quote = FALSE;
                   
$product .= $string{$i};
                }
                else{
                   
$product .= $string{$i};
                }
            }
        }
        return
$product;
    }
}

if( !
function_exists("parse_csv") ){
    function
parse_csv($string){
        global
$cfg;
       
$data = array();
        if(
is_string($string) && ( stripos($string, "\n") !== FALSE )    ){
           
$data = explode("\n", parse_csv_aux($string) );
            foreach(
$data as $key => $row){
               
$columns = array();
               
//$row = strtr(    $row, array( "\";\"" => "\";\"", ";" => " ; " )    );
               
if( stripos($row, " ~ ") !== FALSE ){
                   
$columns = explode( " ~ ", $row );
                    if( !
is_array($columns) )$columns = array( strval($columns) );
                   
$data[$key] = $columns;
                }
            }
            return
$data;
        }
        else if(
is_string($string) && ( stripos( ($string = parse_csv_aux($string)), " ~ ") !== FALSE )    ){
           
$columns = explode( " ~ ", $string );
            if( !
is_array($columns) )$columns = array( strval($columns) );
            return array(
$columns);
        }
        else return
strval($string);
    }
/* end function parse_csv */
} /* end not function exists parse_csv */

if( !function_exists("store_csv_aux") ){
    function
store_csv_aux( $string ){
        global
$cfg;
       
$string = strtr( $string, array( "\n" => "" ) );
       
$product = "";
       
$in_quote = FALSE;
        for(
$i = 0 ; $i < strlen($string) ; $i++ ){
            if(
$string{$i} == $cfg[csvEnc] ){
                if(
$in_quote){
                   
$product .= "\"{$cfg[csvEnc]}";
                }
                else{
                   
$product .= "\"\"{$cfg[csvEnc]}";
                   
$in_quote = TRUE;
                }
            }
            else if(
$string{$i} == "," ){
                if(
$in_quote){
                   
$product .= ",";
                }
                else{
                   
$product .= "\",";
                   
$in_quote = TRUE;
                }
            }
            else{
                if(
$in_quote){
                   
$product .= $cfg[csvEnc];
                   
$in_quote = FALSE;
                   
$product .= $string{$i};
                }
                else{
                   
$product .= $string{$i};
                }
            }
        }
        if(
$in_quote)$product .= $cfg[csvEnc];
        return
$product;
    }
}

if( !
function_exists("store_csv") ){
    function
store_csv($data){
        global
$cfg;
        if(!
is_array($data))return strval($data);
       
$passed_rows = FALSE;
       
$product = "";
        foreach(
$data as $row){
            if(
$passed_rows )$product .= "\n";
            if(
is_array($row) ){
               
$columns = "";
               
$passed_cols = FALSE;
                foreach(
$row as $column){
                    if(
$passed_cols )$columns .= ",";
                   
$columns .= store_csv_aux( $column );
                   
$passed_cols =TRUE;
                }
               
$product .= strval($columns);
            }
            else{
               
$product .= strtr( strval($row), array("\n" => "") );
            }
           
$passed_rows = TRUE;
        }
        return
$product;
    }
/* end function store_csv */
} /* end not function exists store_csv */
?>

[EDIT BY danbrown AT php DOT net: This is a bugfix rewrite of a function originally written by "Alexander Peev".]
bill at eupeople dot net
30-Oct-2008 05:52
hi, really basic function to take blob with full http url's and turn then into "more info" links, handy for page layout etc ;)

<?php
function urltolink($data){

    while (
strpos($wdata, "http")) {

   
$op=strpos($wdata, "http");
   
$rdata=substr($wdata, 0, $op);
   
$ndata=substr($wdata, $op, strlen($wdata)-$op);
   
   
$cp=strpos($ndata, "\n");
   
$link=substr($ndata, 0, $cp);
   
$oc=$op+$cp;
   
$wdata=substr($wdata, $oc, strlen($wdata)-$oc);
   
   
$edata=$edata."$rdata <a href=\"$link\">more info</a><br />";
    }
    return
$edata;
}
?>
mar dot czapla at gmail dot com
24-Oct-2008 02:31
Here we have gr8 function which simply convert ip address to a number using substr with negative offset.
You can need it if you want to compare some IP addresses converted to a numbers.
For example when using ip2country, or eliminating same range of ip addresses from your website :D

<?php

function ip2no($val)
{   
    list(
$A,$B,$C,$D)    =    explode(".",$val);
    return
       
substr("000".$A,-3).
       
substr("000".$B,-3).
       
substr("000".$C,-3).
       
substr("000".$D,-3);
}

$min        =    ip2no("10.11.1.0");
$max        =    ip2no("111.11.1.0");
$visitor    =    ip2no("105.1.20.200");

if(
$min<$visitor && $visitor<$max)   
    {    echo
'Welcome !';    }
else   
    {    echo
'Get out of here !';    }

?>
mr.davin
29-Sep-2008 10:01
Simple use of substr to determine possession:

<?php
function possessive ($word) {
    return 
$word.(substr($word, -1) == 's' ? "'" : "'s");
}

// Davis => Davis'
// Paul => Paul's
?>
NULL_byte
19-Sep-2008 03:21
<?php

function insert_substr($str, $pos, $substr) {
   
$part1 = substr($str, 0, -$pos);
   
$part2 = substr($str, -$pos);
    return
$part1.$substr.$part2;
}

?>
baldaris69 at yahoo dot com
29-Aug-2008 12:57
***Caution newbie***
To extract a file Extension this fuction could be useful.

<?php
$file_extension
= substr($filename , strrpos($filename , '. ') +1);
?>

Suppose your file name is Baldaris.jpeg

strrpos will return the last dot position in the string 9 so

so the compiler will execute substr($filename , 10)

$file_extension will have value jpeg

pretty cool...

Cheer's

Baldaris
post [at] jannik - zappe [dot] de
05-Aug-2008 07:59
Just a little function to cut a string by the wanted amount. Works in both directions.

<?php
function cutString($str, $amount = 1, $dir = "right")
{
  if((
$n = strlen($str)) > 0)
  {
    if(
$dir == "right")
    {
     
$start = 0;
     
$end = $n-$amount;
    } elseif(
$dir == "left") {
     
$start = $amount;
     
$end = $n;
    }
   
    return
substr($str, $start, $end);
  } else return
false;
}
?>

Enjoy ;)
jamesvanboxtel at wsu dot edu
31-Jul-2008 02:17
Here is a quick function to get the substring of a string up to and including the last occurrence of $needle

<?php
function substrtruncate($string, $needle)
{
    return
substr($string, 0, strrpos($string, $needle)+1);
}

$current_dir = substrtruncate($_SERVER['SCRIPT_NAME'], '/');
?>
Anonymous
29-Jul-2008 11:18
I wrote this simple function to limit the middle characters of a string to a specified length.

<?php
$input
= "hello world"
echo(limitchrmid($imput,10)) // hel ... rld

//limit chars middle
function limitchrmid($value,$lenght){
    if (
strlen($value) >= $lenght ){
       
$lenght_max = ($lenght/2)-3;
       
$start = strlen($value)- $lenght_max;
       
$limited = substr($value,0,$lenght_max);
       
$limited.= " ... ";                  
       
$limited.= substr($value,$start,$lenght_max);
    }
    else{
       
$limited = $value;
    }
    return
$limited;
}
?>
svihel
27-Jun-2008 01:09
joao dot martins at plako dot net
26-Mar-2008 09:14

ben at enemy dot dk
10-Feb-2008 05:48

Updated function. The previous one will return empty value if the $string has no letter spaces. This is usefull if some of your strings have only one word.

<?php
function cutText($string, $setlength) {
   
$length = $setlength;
    if(
$length<strlen($string)){
        while ((
$string{$length} != " ") AND ($length > 0)) {
           
$length--;
        }
        if (
$length == 0) return substr($string, 0, $setlength);
        else return
substr($string, 0, $length);
    }else return
$string;
}
?>
serzh at nm dot ru
03-Jun-2008 03:13
easy and quick way to limit length of a text by not cutting full words:

textLimit('some words', 7) is 'some...'

<?php
function textLimit($string, $length, $replacer = '...')
{
  if(
strlen($string) > $length)
  return (
preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
 
  return
$string;
}
?>
Anonymous
17-Mar-2008 04:53
Split a string to an array of strings specified by an array of lengths:

<?php
function split_by_lengths($inString, $arrayLengths)
{
   
$output = array();
    foreach (
$arrayLengths as $oneLength)
    {
       
$output[] = substr($inString, 0, $oneLength);
       
$inString = substr($inString, $oneLength);
    }
    return (
$output);
}
?>
split_by_lengths('teststringtestteststring', array(4,6,4,4,6)) returns:
array('test','string','test','test','string')

Don't use it on user input without some error handling!
kriskra at gmail dot com
29-Feb-2008 05:21
The javascript charAt equivalent in php of felipe has a little bug. It's necessary to compare the type (implicit) aswell or the function returns a wrong result:
<?php
function charAt($str,$pos) {
    return (
substr($str,$pos,1) !== false) ? substr($str,$pos,1) : -1;
}
?>
Anonymous
22-Feb-2008 05:12
I've used the between, after, before, etc functions that biohazard put together for years and they work great.  I've also added to it a new function that I use a lot and thought others might like it as well.  It uses his before/after functions so they are required to use it.

<?php
$example_html
= "<p>test1 Test2</p><title>hi there</title><p>Testing</p>";
$paragraph_text = multi_between('<p>', '</p>', $example_html);

//Prints an arry of:
//Array ( [1] => test1 Test2 [2] => Testing )
print_r($paragraph_text);

function
multi_between($this, $that, $inthat)
{
  
$counter = 0;
   while (
$inthat)
   {
     
$counter++;
     
$elements[$counter] = before($that, $inthat);
     
$elements[$counter] = after($this, $elements[$counter]);
     
$inthat = after($that, $inthat);
   }
   return
$elements;
}
//Get the help functions from biohazard's post below.
?>
highstrike at gmail dot com
05-Jan-2008 08:47
Because i didnt see a function that would cut a phrase from a text (article or whatever) no matter where, front/middle/end and add ... + keeping the words intact, i wrote this:

Usage:
- The parameter $value if array will need the whole text and the portion you want to start from, a string. EG: cuttext(array($text, $string), 20). If the string is "have" and is near the beginning of the text, the function will cut like "I have a car ...", if the string is in the middle somewhere it will cut like "... if you want to have your own car ..." and if its somewhere near the end it will cut like "... and you will have one."
- The $length parameter is self explanatory.

Note: if you have just a string "127hh43h2h52312453jfks2" and you want to cut it, just use the function like so: cuttext($string, 10) and it will cut it like "127hh43h2h..."

<?php

////////////////////////////////////////////////////////
// Function:         cuttext
// Description: Cuts a string and adds ...

function cuttext($value, $length)
{   
    if(
is_array($value)) list($string, $match_to) = $value;
    else {
$string = $value; $match_to = $value{0}; }

   
$match_start = stristr($string, $match_to);
   
$match_compute = strlen($string) - strlen($match_start);

    if (
strlen($string) > $length)
    {
        if (
$match_compute < ($length - strlen($match_to)))
        {
           
$pre_string = substr($string, 0, $length);
           
$pos_end = strrpos($pre_string, " ");
            if(
$pos_end === false) $string = $pre_string."...";
            else
$string = substr($pre_string, 0, $pos_end)."...";
        }
        else if (
$match_compute > (strlen($string) - ($length - strlen($match_to))))
        {
           
$pre_string = substr($string, (strlen($string) - ($length - strlen($match_to))));
           
$pos_start = strpos($pre_string, " ");
           
$string = "...".substr($pre_string, $pos_start);
            if(
$pos_start === false) $string = "...".$pre_string;
            else
$string = "...".substr($pre_string, $pos_start);
        }
        else
        {       
           
$pre_string = substr($string, ($match_compute - round(($length / 3))), $length);
           
$pos_start = strpos($pre_string, " "); $pos_end = strrpos($pre_string, " ");
           
$string = "...".substr($pre_string, $pos_start, $pos_end)."...";
            if(
$pos_start === false && $pos_end === false) $string = "...".$pre_string."...";
            else
$string = "...".substr($pre_string, $pos_start, $pos_end)."...";
        }

       
$match_start = stristr($string, $match_to);
       
$match_compute = strlen($string) - strlen($match_start);
    }
   
    return
$string;
}

?>
morgangalpin att gmail dotty com
24-Sep-2007 10:55
Adding the $limit parameter introduced a bug that was not present in the original. If $limit is small or negative, a string with a length exceeding the limit can be returned. The $limit parameter should be checked. It takes slightly more processing, but it is dwarfed in comparison to the use of strlen().

<?php
 
function short_name($str, $limit)
  {
   
// Make sure a small or negative limit doesn't cause a negative length for substr().
   
if ($limit < 3)
    {
     
$limit = 3;
    }

   
// Now truncate the string if it is over the limit.
   
if (strlen($str) > $limit)
    {
      return
substr($str, 0, $limit - 3) . '...';
    }
    else
    {
      return
$str;
    }
  }
?>
corphi
12-Sep-2007 04:06
I prefer
<?php
function short_name($str, $limit)
{
    return
strlen($str) > $limit ? substr($str, 0, $limit - 3) . '...' : $str;
}
?>

Now, every returned string has a maximum length of $limit chars (instead of $limit + 3).
Petez
31-Aug-2007 03:56
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:

<?php
/* substr access */
beginTimer();
for (
$i = 0; $i < 1500000; $i++){
   
$opening = substr($string,0,11);
    if (
$opening == 'Lorem ipsum'){
       
true;
    }else{
       
false;
    }
}
$endtime1 = endTimer();

/* direct access */
beginTimer();
for (
$i = 0; $i < 1500000; $i++){
    if (
$string[0] == 'L' && $string[1] == 'o' && $string[2] == 'r' && $string[3] == 'e' && $string[4] == 'm' && $string[5] == ' ' && $string[6] == 'i' && $string[7] == 'p' && $string[8] == 's' && $string[9] == 'u' && $string[10] == 'm'){
       
true;
    }else{
       
false;
    }
}
$endtime2 = endTimer();

/* strstr access */
beginTimer();
for (
$i = 0; $i < 1500000; $i++){
   
$opening = strstr($string,'Lorem ipsum');
    if (
$opening == true){
       
true;
    }else{
       
false;
    }
}
$endtime3 = endTimer();

echo
$endtime1."\r\n".$endtime2."\r\n".$endtime3;
?>

The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:

(substr) 3.24
(direct access) 11.49
(strstr) 4.96

(With standard deviations 0.01, 0.02 and 0.04)

THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.
ein at anti-logic dot com
30-Jul-2007 03:06
If you need to divide a large string (binary data for example) into segments, a much quicker way to do it is to use streams and the php://memory stream wrapper.

For example, if you have a large string in memory, write it to a memory stream like
<?php
$segment_length
= 8192; // this is how long our peice will be
$fp = fopen("php://memory", 'r+'); // create a handle to a memory stream resource
fputs($fp, $payload); // write data to the stream
$total_length=ftell($fp); // get the length of the stream
$payload_chunk = fread ( $fp, $segment_length  );
?>

Working with large data sets, mine was 21MB, increased the speed several factors.
Robert Chapin
26-Jun-2007 02:40
All the references to "curly braces" on this page appear to be obsolete.

According to http://us.php.net/manual/en/language.types.string.php

"Using square array-brackets is preferred because the {braces} style is deprecated as of PHP 6."

Robert Chapin
Chapin Information Services
lanny at freemail dot hu
26-Jun-2007 03:31
Starting from version 5.2.3 if $start is negative and larger then the length of the string, the result is an empty string, while in earlier versions the result was the string itself!

substr ("abcdef", -1000);

result in 5.2.0
'abcdef'

result in 5.2.3
''

This is a small inconsistency, one of those things that makes the life of a PHP programmer like hell.
Antoine
10-May-2007 09:08
The functions submitted below are a waste of time and memory. To convert a string to an integer or a trimmed float, use the built in conversion instead of parsing the string, e.g :

<?php
$x
= "27.2400";
echo (float)
$x; // 27.24
echo (int)$x; // 27
?>
siavashg at gmail dot com
06-Mar-2007 01:51
A further addition to Jean-Felix function to extract data between delimeters.

The previous function wouldn't return the correct data if the delimeters used where long than one char. Instead the following function should do the job.

<?php
function extractBetweenDelimeters($inputstr,$delimeterLeft,$delimeterRight) {
  
$posLeft  = stripos($inputstr,$delimeterLeft)+strlen($delimeterLeft);
  
$posRight = stripos($inputstr,$delimeterRight,$posLeft+1);
   return 
substr($inputstr,$posLeft,$posRight-$posLeft);
}
?>
Jean-Felix, Bern
28-Feb-2007 07:10
If you need to extract information in a string between delimeters then you can use this:

Inputstring is:
"Heidi Klum Supermodel" <info@HeidiKlum.com>

Here the script
<?php
   $emailadresse
= "\"Heidi Klum Supermodel\" <info@HeidiKlum.com>";
  
  
$outputvalue = extractBetweenDelimeters($emailadresse,"\"","\"");
   echo 
$outputvalue// shows Heidi Klum Supermodel
  
echo "<br>";
  
$outputvalue = extractBetweenDelimeters($emailadresse,"<",">");
   echo 
$outputvalue// shows info@HeidiKlum.com
  
  
  
function extractBetweenDelimeters($inputstr,$delimeterLeft,$delimeterRight) {
   
$posLeft  = stripos($inputstr,$delimeterLeft)+1;
   
$posRight = stripos($inputstr,$delimeterRight,$posLeft+1);
    return 
substr($inputstr,$posLeft,$posRight-$posLeft);
   }
  
?>
ijavier aka(not imatech) igjav
14-Feb-2007 02:20
<?php
/*
    An advanced substr but without breaking words in the middle.
    Comes in 3 flavours, one gets up to length chars as a maximum, the other with length chars as a minimum up to the next word, and the other considers removing final dots, commas and etcteteras for the sake of beauty (hahaha).
   This functions were posted by me some years ago, in the middle of the ages I had to use them in some corporations incorporated, with the luck to find them in some php not up to date mirrors. These mirrors are rarely being more not up to date till the end of the world... Well, may be am I the only person that finds usef not t bre word in th middl?

Than! (ks)

This is the calling syntax:

    snippet(phrase,[max length],[phrase tail])
    snippetgreedy(phrase,[max length before next space],[phrase tail])

*/

function snippet($text,$length=64,$tail="...") {
   
$text = trim($text);
   
$txtl = strlen($text);
    if(
$txtl > $length) {
        for(
$i=1;$text[$length-$i]!=" ";$i++) {
            if(
$i == $length) {
                return
substr($text,0,$length) . $tail;
            }
        }
       
$text = substr($text,0,$length-$i+1) . $tail;
    }
    return
$text;
}

// It behaves greedy, gets length characters ore goes for more

function snippetgreedy($text,$length=64,$tail="...") {
   
$text = trim($text);
    if(
strlen($text) > $length) {
        for(
$i=0;$text[$length+$i]!=" ";$i++) {
            if(!
$text[$length+$i]) {
                return
$text;
            }
        }
       
$text = substr($text,0,$length+$i) . $tail;
    }
    return
$text;
}

// The same as the snippet but removing latest low punctuation chars,
// if they exist (dots and commas). It performs a later suffixal trim of spaces

function snippetwop($text,$length=64,$tail="...") {
   
$text = trim($text);
   
$txtl = strlen($text);
    if(
$txtl > $length) {
        for(
$i=1;$text[$length-$i]!=" ";$i++) {
            if(
$i == $length) {
                return
substr($text,0,$length) . $tail;
            }
        }
        for(;
$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;}
       
$text = substr($text,0,$length-$i+1) . $tail;
    }
    return
$text;
}

/*
echo(snippet("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetwop("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetgreedy("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea"));
*/
?>
persisteus at web dot de
13-Feb-2007 07:45
Here is also a nice (but a bit slow) alternative for colorizing an true color image:

<?php
// $colorize = hexadecimal code in String format, f.e. "10ffa2"
// $im = the image that have to be computed

$red = hexdec(substr($colorize, 0, 2));
$green = hexdec(substr($colorize, 2, 2));
$blue = hexdec(substr($colorize, 4, 2));

$lum_c = floor(($red*299 + $green*587 + $blue*144) / 1000);

for (
$i = 0; $i < $lum_c; $i++)
{
 
$r = $red * $i / $lum_c;
 
$g = $green * $i / $lum_c;
 
$b = $blue * $i / $lum_c;
 
$pal[$i] = $r<<16 | $g<<8 | $b;
}
$pal[$lum_c] = $red<<16 | $green<<8 | $blue;
for (
$i = $lum_c+1; $i < 255; $i++)
{
 
$r = $red + (255-$red) * ($i-$lum_c) / (255-$lum_c);
 
$g = $green + (255-$green) * ($i-$lum_c) / (255-$lum_c);
 
$b = $blue + (255-$blue) * ($i-$lum_c) / (255-$lum_c);
  </