tags:

views:

156

answers:

3

I'm looking to create a php function that can trim each line in a long string.

eg:

<?php
$txt = <<< HD
    This is text.
          This is text.
  This is text.
HD;

echo trimHereDoc($txt);

output:

This is text.
This is text.
This is text.

Yes, I know about the trim() function. Just not sure how to use it on a long strings such as heredoc.

+3  A: 

Simple solution

<?php
$txtArray = explode("\n", $txt);
$txtArray = array_map('trim', $txtArray);
$txt = implode("\n", $txtArray);
erenon
+1 because we had the same idea
gpilotino
+7  A: 
function trimHereDoc($t)
 {
 return implode("\n", array_map('trim', explode("\n", $t)));
 }
gpilotino
+1 becouse the more generic solution. (but, I don't like so compact lines)
erenon
+1  A: 
function trimHereDoc($txt)
{
    return preg_replace('/^\s+|\s+$/m', '', $txt);
}

^\s+ matches whitespace at the start of a line and \s+$ matches whitespace at the end of a line. The m flag says to do multi-line replacement so ^ and $ will match on any line of a multi-line string.

John Kugelman
nice RE. need to keep snippets of this.
Yada