Padding and Stripping a String For formatting reasons, you sometimes need to modify the string length via either padding or stripping characters. PHP provides a number of functions for doing so. This section examines many of the commonly used functions. Trimming Characters from the Beginning of a String Theltrim()function removes various characters from the beginning of a string, including white space, the horizontal tab (\t), newline (\n), carriage return (\r),NULL(\0), and vertical tab (\x0b). Its prototype follows: string ltrim(string str [, string charlist]) You can designate other characters for removal by defining them in the optional parametercharlist. Trimming Characters from the End of a String Thertrim()function operates identically toltrim(), except that it removes the designated characters from the right side of a string. Its prototype follows: string rtrim(string str [, string charlist]) Trimming Characters from Both Sides of a String You can think of thetrim()function as a combination ofltrim()andrtrim(), except that it removes the designated characters from both sides of a string: string trim(string str [, string charlist]) Padding a String Thestr_pad()function pads a string with a specified number of characters. Its prototype follows: string str_pad(string str, int length [, string pad_string [, int pad_type]]) If the optional parameterpad_stringis not defined,strwill be padded with blank spaces; otherwise, it will be padded with the character pattern specified bypad_string. By default, the string will be padded to the right; however, the optional parameterpad_typemay be assigned the valuesSTR_PAD_RIGHT,STR_PAD_LEFT, orSTR_PAD_BOTH, padding the string accordingly. This example shows how to pad a string usingstr_pad(): <?php This returns the following: -------------------------------------------- This example makes use ofstr_pad()’s optional parameters: <?php This returns the following: -------------------------------------------- Note thatstr_pad()truncates the pattern defined bypad_stringiflengthis reached before completing an entire repetition of the pattern.
blog comments powered by Disqus |
|
|
|
|
|
|
|