You want to remove whitespace from the beginning or end of a string. Whitespace is defined as the following characters: newline, carriage return, space, horizontal and vertical tab, and null.
Use trim($string [, charlist]), rtrim(), or ltrim(). ltrim() removes whitespace from the beginning of a string, rtrim() from the end of a string, and trim() from both beginning and end of a string. If you want to specify characters other than the whitespace, you can list all characters in the second optional argument, charlist.
The whitespaces are: " ", "\t", "\n", "\r", "\0" (the NULL-byte), and "\x0B" (vertical tab).
Use str_pad($string, $pad_length [, $pad_string [, $pad_type]]) to pad strings. The default is to pad with spaces on the right side of the string.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php $string = " Today is a very beautiful day "; echo "<p><pre>$string</pre></p>"; echo "trim() strips whitespaces from the beginning and end.<br />"; echo "<p><pre>", trim($string), "</pre></p>"; echo "rtrim() strips whitespaces on the right side.<br />"; echo "<p><pre>", rtrim($string), "</pre></p>"; echo "ltrim() strips whitespaces on the left side.<br />"; echo "<p><pre>", ltrim($string), "</pre></p>"; echo "tab tab Hello newline.<br />"; $hello ="\t\tHello\n"; echo "<p><pre>$hello</pre></p>"; echo "trim() strips tabs and newline.<br />"; echo "<p><pre>", trim($hello), "</pre></p>"; echo "rtrim() strips newline on the right side.<br />"; echo "<p><pre>", rtrim($hello), "</pre></p>"; echo "ltrim() strips 2 tabs on the left side.<br />"; echo "<p><pre>", ltrim($hello), "</pre></p>"; $hello ="****Hello****"; echo "<p><pre>$hello</pre></p>"; echo "trim() strips all *.<br />"; echo "<p><pre>", trim($hello, "*"), "</pre></p>"; echo "rtrim() strips * on the right side.<br />"; echo "<p><pre>", rtrim($hello, "*"), "</pre></p>"; echo "ltrim() strips * on the left side.<br />"; echo "<p><pre>", ltrim($hello, "*"), "</pre></p>"; echo str_pad("Padding String", 30, "-=", STR_PAD_BOTH), "<br />"; $name = "John Doe"; $prof = "Anonymous"; echo "<pre>"; echo str_pad("Name:", 15).$name, "<br />"; echo str_pad("Profession:", 15).$prof, "<br />"; echo "</pre>"; ?> </p> </body> </html> |