无法在 PHP 中将空格添加到字符串中


Can't get whitespace added to string in PHP

我正在尝试制作一个 Web 表单,该表单逐行输出到平面文本文件,该表单的输入是什么。 其中几个字段不是必需的,但输出文件必须为未填写的内容输入空格。 这是我正在尝试的:

$output = $_SESSION["emp_id"];
if(!empty($_POST['trans_date'])) {
    $output .= $_POST["trans_date"];
}else{
$output = str_pad($output, 6);
}
if(!empty($_POST['chart'])) {
    $output .= $_POST["chart"];
}else{
    $output = str_pad($output, 6);
}
write_line($output);
function write_line($line){
        $file = 'coh.txt';
        // Open the file to get existing content
        $current = file_get_contents($file);
        // Append a new line to the file
        $current .= $line . PHP_EOL;
        // Write the contents back to the file
        file_put_contents($file, $current);
    }

但是,当我检查我的输出时,空格没有显示。 关于这是怎么回事的任何想法? 提前感谢!

str_pad填充空格,而不是添加空格。您正在用空格填充现有值,使其长度为 6 个字符,而不是向值添加 6 个空格。因此,如果$_SESSION["emp_id"]长度为 6 个字符或更多,则不会添加任何内容。

str_pad() 不会添加该数量的空格,而是通过添加适当数量的空格来使字符串达到该长度。尝试str_repeat():

$output = $_SESSION["emp_id"];
if(!empty($_POST['trans_date'])) {
    $output .= $_POST["trans_date"];
}else{
    $output = $output . str_repeat(' ', 6);
}
if(!empty($_POST['chart'])) {
    $output .= $_POST["chart"];
}else{
    $output = $output . str_repeat(' ', 6);
}
write_line($output);
function write_line($line) {
    $file = 'coh.txt';
    // Open the file to get existing content
    $current = file_get_contents($file);
    // Append a new line to the file
    $current .= $line . PHP_EOL;
    // Write the contents back to the file
    file_put_contents($file, $current);
}

干杯!