开发者

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

开发者 https://www.devze.com 2022-12-09 18:53 出处:网络
I\'m looking to create a PHP function that can trim each line in a long string. For example, <?php $txt = <<< HD

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 te开发者_运维问答xt.

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


function trimHereDoc($t)
{
    return implode("\n", array_map('trim', explode("\n", $t)));
}


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.


Simple solution

<?php
$txtArray = explode("\n", $txt);
$txtArray = array_map('trim', $txtArray);
$txt = implode("\n", $txtArray);


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消