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

后端 未结 4 2543
囚心锁ツ
囚心锁ツ 2021-02-20 14:23

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

For example,



        
相关标签:
4条回答
  • 2021-02-20 14:32
    function trimHereDoc($t)
    {
        return implode("\n", array_map('trim', explode("\n", $t)));
    }
    
    0 讨论(0)
  • 2021-02-20 14:36
    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.

    0 讨论(0)
  • 2021-02-20 14:36
    function trimHereDoc($txt)
    {
        return preg_replace('/^\h+|\h+$/m', '', $txt);
    }
    

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

    0 讨论(0)
  • 2021-02-20 14:38

    Simple solution

    <?php
    $txtArray = explode("\n", $txt);
    $txtArray = array_map('trim', $txtArray);
    $txt = implode("\n", $txtArray);
    
    0 讨论(0)
提交回复
热议问题