Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim each line in a heredoc (long string) in PHP

Tags:

string

php

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

For example,

<?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, but I am just not sure how to use it on a long strings such as heredoc.

like image 896
Yada Avatar asked Oct 31 '09 18:10

Yada


4 Answers

function trimHereDoc($t)
{
    return implode("\n", array_map('trim', explode("\n", $t)));
}
like image 63
gpilotino Avatar answered Nov 17 '22 18:11

gpilotino


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.

like image 11
John Kugelman Avatar answered Nov 17 '22 19:11

John Kugelman


Simple solution

<?php
$txtArray = explode("\n", $txt);
$txtArray = array_map('trim', $txtArray);
$txt = implode("\n", $txtArray);
like image 6
erenon Avatar answered Nov 17 '22 18:11

erenon


function trimHereDoc($txt)
{
    return preg_replace('/^\h+|\h+$/m', '', $txt);
}

While \s+ removes empty lines, keeps \h+ each empty lines

like image 5
jokumer Avatar answered Nov 17 '22 18:11

jokumer