The trim() function is used to remove white space and other predefined characters from both sides of a string.
trim ( $string , $character) : string
Parameter Name | Descrption |
---|---|
$string | Required, String to be remove whitespace/predefined characters |
$character | Optional, The trim() function return the string with whitespace removed, if second parameter will not passed then trim() will strip these characters: |
The trimmed string
$string1 = " this is string "; //length : 16 $trim_string1 = trim($string1); var_dump($trim_string1); //output : 'this is string' (length=14) $text_trim = "\t\tThis is string "; var_dump($text_trim); //output : ' This is string ' (length=17) $trimmed = trim($text_trim); var_dump($trimmed); // output : 'This is string' (length=14) $text_trim = "Trim function in PHP"; $trimmed = trim($text_trim,'TP'); var_dump($trimmed); // output : 'rim function in PH' (length=18) $text_trim = "Trim function in PHPT"; $trimmed = trim($text_trim,'T'); var_dump($trimmed); //output : 'rim function in PHP' (length=19)
$lang = array('PHP ',' JS ',' NodeJS'); var_dump($lang); //output array (size=3) 0 => string 'PHP ' (length=4) 1 => string ' JS ' (length=4) 2 => string ' NodeJS' (length=7) $newarray = array_map('trim', $lang); var_dump($newarray); //output array (size=3) 0 => string 'PHP' (length=3) 1 => string 'JS' (length=2) 2 => string 'NodeJS' (length=6)
function trim_array_value(&$value) { $value = trim($value); } $lang = array('PHP ',' JS ',' NodeJS'); array_walk($lang, 'trim_array_value'); var_dump($lang);
$lang = array('PHP ',' JS ',' NodeJS','frontend'=>array(' html ','CSS ')); function TrimMultiDimensional(&$array) { foreach($array as &$value) is_array($value) ? TrimMultiDimensional($value):$value=trim($value); unset($value); } TrimMultiDimensional($lang); var_dump($lang);
Related Functions