trim 


string apg

STRIP whitespaces and selected characters from the beginning and the end of a STRING.





This function returns a string with whitespace stripped from the beginning and the end of $str if $character_mask is not provided.



<?php

str trim 
str $str [, str $character_mask ] )


where,

$str The input STRING

$character_mask 
The list of additional characters 
                                to strip from the beginning 
and the end

?>
 

$str


The input STRING.



$character_mask

The additional characters list to be striped:

DEFAULT ASCII VALUE
" " 32 0x20 ESPAÇO
"\t" 9 0x09 TAB H
"\n" 10 0x0A NL
"\r" 13 0x0D CR
"\0" 0 0x00 NULL
"\x0B" 11 0x0B TAB V
ed48


  1 EXERCISE   

<?php

$strl01a 
'            QUOSQUE TANDEM?          ';

$strl01b trim($strl01a);

echo 
$strl01b '<br><br>';


$strl01c '            QUOSQUE TANDEM?          ';

$strl01d trim($strl01c);
    
echo 
$strl01d;

?> 

 RESULT   

QUOSQUE TANDEM?

QUOSQUE TANDEM?


  2 EXERCISE   

 <?php

$strl02a 
'-/--//---///----QUOSQUE TANDEM?-/--//---///----';

$strl02b trim($strl02a'"-", "/"');

echo 
$strl02b '<br><br>';

/* ---------------------------------------

    list of characters defined by
   a range of ASCII hexadecimal values
   
   '0x29,..0x30' -> from 0x29 to 0x30
   
   --------------------------------------- */

$strl02c '-/--//---///----QUOSQUE TANDEM?-/--//---///----';

$strl02d trim($strl02c'0x29, ..0x30');
    
echo 
$strl02d;

?> 

 RESULT   

 QUOSQUE TANDEM?

QUOSQUE TANDEM?


  3 EXERCISE   

<?php

$tests 
= <<<TESTS
'ABC' ===  trim('ABC')
'ABC' === ltrim('ABC')
'ABC' === rtrim('ABC')
'ABC' ===  trim(" \\0\\t\\nABC \\0\\t\\n")
"ABC \\0\\t\\n" === ltrim(" \\0\\t\\nABC \\0\\t\\n")
" \\0\\t\\nABC" === rtrim(" \\0\\t\\nABC \\0\\t\\n")
" \\0\\t\\nABC \\0\\t\\n" ===  trim(" \\0\\t\\nABC \\0\\t\\n",'')
" \\0\\t\\nABC \\0\\t\\n" === ltrim(" \\0\\t\\nABC \\0\\t\\n",'')
" \\0\\t\\nABC \\0\\t\\n" === rtrim(" \\0\\t\\nABC \\0\\t\\n",'')
"ABC\\x50\\xC1" === trim("ABC\\x50\\xC1\\x60\\x90","\\x51..\\xC0")
"ABC\\x50" === trim("ABC\\x50\\xC1\\x60\\x90","\\x51..\\xC1")
"ABC" === trim("ABC\\x50\\xC1\\x60\\x90","\\x50..\\xC1")
"ABC\\x50\\xC1" === trim("ABC\\x50\\xC1\\x60\\x90","\\x51..\\xC0")
"ABC\\x50" === trim("ABC\\x50\\xC1\\x60\\x90","\\x51..\\xC1")
"ABC" === trim("ABC\\x50\\xC1\\x60\\x90","\\x50..\\xC1")
TESTS;

include(
__DIR__ '/quicktester.inc');

?>

<?php
 
/*
   
  // quicktester.inc
 
  Helper for simple tests to check return-value. Usage:

  $tests = <<<TESTS
   expected_return_value === expression
   2                     === 1+1
   4                     === 2*2
   FALSE                 === @ fopen('non_existent_file')
TESTS;
  include( 'tests/quicktester.inc' );

  Expect: OK

  Remember to NOT put a trailing ; after a line!

 */
error_reporting(E_ALL);
$tests explode("\n",$tests);
$success TRUE;
foreach (
$tests as $n=>$test)
{
    
// ignore empty lines
    
if (!$test) continue;

    
// warn for trailing ;
    
if (substr(trim($test), -11) === ';') {
        echo 
"WARNING: trailing ';' found in test ".($n+1)."\n";
        exit;
    }

    
// try for operators
    
$operators = array('===''~==');
    
$operator NULL;
    foreach (
$operators as $a_operator) {
        if (
strpos($test$a_operator)!== FALSE) {
            
$operator $a_operator;
            list(
$left,$right) = explode($operator$test);
            break;
        }
    }
    if (!
$operator) {
        echo 
"WARNING: unknown operator in '$test' (1)\n";
        exit;
    }

    
$left  = eval("return ($left );");
    
$right = eval("return ($right);");
    switch (@
$operator) {
        case 
'==='// exact match
            
$result $left === $right;
            break;
        case 
'~=='// may differ after 12th significant number
            
if (   !is_float($left ) && !is_int($left )
                || !
is_float($right) && !is_int($right)) {
                
$result FALSE;
                break;
            }
            
$result abs(($left-$right) / $left) < 1e-12;
            break;
        default:
            echo 
"WARNING: unknown operator in '$test' (2)\n";
            exit;
    }

    
$success $success && $result;
    if (!
$result) {
        echo 
"\nAssert failed:\n";
        echo 
"$test\n";
        echo 
"Left:  ";var_dump($left );
        echo 
"Right: ";var_dump($right);
    }
}
if (
$success) echo "OK";

  4 EXERCISE   

<?php

/* trim with unset/null/boolean variable - 
 * returns an empty string */

$null_var NULL;
var_dumptrim($null_var) );
echo 
"<br><br>";
$null_var "";
var_dumptrim($null_var) );
echo 
"<br><br>";
$null_var 0;
var_dumptrim($null_var) );
echo 
"<br><br>";
$bool_val true;
var_dumptrim($null_var) );
echo 
"<br><br>";

/* second argument charlist as null - 
 * does not trim any white spaces */
var_dumptrim("\ttesting trim""") );
echo 
"<br><br>";
var_dumptrim("  \ttesting trim  "NULL) );
echo 
"<br><br>";
var_dumptrim("\ttesting trim  "true) );

/* Use of class and objects */
echo "<br><br>Testing with OBJECTS:<br>";
class 
string1
{
  public function 
__toString() {
    return 
"Object";
  }
}
$obj = new string1;
var_dumptrim($obj"Ot") );

/* String with embedded NULL */
echo "<br><br>Testing with String 
                      with embedded NULL:<br>"
;
var_dumptrim("\x0n1234\x0005678
\x0000efgh\xijkl\x0n1"
"\x0n1") );

/* heredoc string */
$str = <<<EOD
us
ing heredoc string
EOD;

echo 
"<br><br>Testing with heredoc string:<br>";
var_dumptrim($str"us\ning") );

?>

  5 EXERCISE   

<?php

echo "Testing trim() : basic functionality.<br>";

$text  "  \t\r\n\0\x0B  ---These are a few words---  \t\r\n\0\x0B  ";
$hello  "!===Hello World===!";
$binary "\x0A\x0DExample string\x0A\x0D";

echo 
"<br><br>Trim string with all white space characters:<br>";
var_dump(trim($text));

echo 
"<br><br>Trim non-whitespace from a string:<br>";
var_dump(trim($hello"=!"));

echo 
"<br><br>Trim some non-white space characters
                             from a string:<br>"
;
var_dump(trim($hello"Hdle"));

echo 
"<br><br>Trim the ASCII control characters 
             at the beginning of a string:<br>"
;
var_dump(trim($binary"\x00..\x1F"));

?>

  6 EXERCISE   

<?php

echo "Testing trim() : error conditions.<br>";

$hello "  Hello World\n";
echo 
"<br><br>Test trim function with 
                             various invalid charlists:<br>"
;
var_dump(trim($hello"..a"));
echo 
"<br><br>";
var_dump(trim($hello"a.."));
echo 
"<br><br>";
var_dump(trim($hello"z..a"));
echo 
"<br><br>";
var_dump(trim($hello"a..b..c"));

?>