Handy string manipulation functions

Many people like to keep their code tidy, even the final HTML that you can see when selecting "Show source" option in your browser. This includes having correct number of indents for all levels.

It would make the code cluttered and messy if we had to define that we wanted so many tabs to be prepended or a new line character appended (like many often do - $text . "\n").

Here are two functions to avoid that - printLn and sprintLn - they print the text and return the text respectively.

As the name suggests, printLn prints $text with the specified number of tabs prepended and a new line charater appended:

  1. <?php
  2.  
  3. /**
  4.  * Print text with a new line character appended
  5.  *
  6.  * @param string $text Text to print
  7.  */
  8. function printLn($text, $indent_tabs = 0) {
  9.     $tabs = ($indent_tabs > 0) ? str_repeat("\t", $indent_tabs) : '';
  10.     print $tabs . $text . "\n";
  11. }

The second function does exactly the same except instead of printing it returns that string:

  1. <?php
  2.  
  3. /**
  4.  * Return text with a new line character appended
  5.  *
  6.  * @param string $text  Text to print
  7.  * @return string $text Text with \n appended
  8.  */
  9. function sprintLn($text, $indent_tabs = 0) {
  10.     $tabs = ($indent_tabs > 0) ? str_repeat("\t", $indent_tabs) : '';
  11.     return $tabs . $text . "\n";
  12. }

This function could be used for many things. Some of the examples would include command line scripts where you need to print lines of status text or (text) file generation scripts printing lines. I personally use these functions in cases when I need to print HTML code, like in this example:

  1. printLn('<ul>', 2);
  2. for ($i = 0; $i < 10; $i++) {
  3.     printLn('<li>' . $i . '</li>', 3);
  4. }
  5. printLn('</ul>', 2);

This example would print an HTML code with correct indentation (UL tag would be prepended with 2 tabs, the LI elements would be prepended with 3 tabs):

  1.         <ul>
  2.             <li>0</li>
  3.             <!-- nodes 1-8 -->
  4.             <li>9</li>
  5.         </ul>

Enjoy!

Comments
No comments
Name
Email (required)
will not be published
Website
Recaptcha
you will only be required to fill it in once in this session

You can use [code][/code] tags in your comments