如何在字符串末尾添加多个空格?

时间:2021-05-18 08:31:34

标签: php

我正在尝试在单词末尾添加空格,使其看起来与下一个单词对齐。我试过 str_padstr_replace 但没有用。

    $str = array("one", "two", "three", "four", "five", "six");

    ///with str_pad
    foreach ($str as $value) {
        if (strlen($value) <= 5) {
            $pad_str = str_pad($value, 6, " ", STR_PAD_RIGHT);
            $result = $pad_str.'bar';
            echo $result.'<br>';
        }
    }
    ///with str_replace
    foreach ($str as $value) {
        if (strlen($value) <= 5) {
            $rep_str = str_repeat(" ", max(0, 6 - strlen($value)));
            $result = $value.$rep_str.'bar';
            echo $result.'<br>';
        }
    }

我想要这样的东西:

//output I want            //output returned
one   bar                  one bar
two   bar                  two bar
three bar                  three bar
four  bar                  four bar
five  bar                  five bar
six   bar                  six bar

我怎样才能做到这一点。我已经尝试了几个小时,但没有找到正确的答案。所以请帮忙。

2 个答案:

答案 0 :(得分:0)

您可以使用 PHP_EOL 并添加 <pre></pre> 标签以根据需要显示您的结果:

<?php

 $str = array("one", "two", "three", "four", "five", "six");

echo '<pre>';    

    ///with str_pad
    foreach ($str as $value) {
        if (strlen($value) <= 5) {
            $pad_str = str_pad($value, 6, " ", STR_PAD_RIGHT);
            $result = $pad_str.'bar';
            echo $result.PHP_EOL;
        }
    }

echo '</pre>';

Online

答案 1 :(得分:0)

只需找到数组中值的最大长度并相应地重复空格。

喜欢

$str = array("one", "two", "three", "four", "five", "six");
$max_len = max(array_map('strlen', $str)); // max length of value in array

echo "<pre>";

foreach ($str as $value) {
     $add_space = $max_len - strlen($value); 
     echo $value.str_repeat('&nbsp;', $add_space + 1)."bar"; echo "<br>";
}

echo "</pre>";