将两个字符串与 for 循环组合在一起


Combine two strings with for loop

是否可以将两个字符串与for循环组合在一起?例如:

echo 'Prefix '.for($i=0;$i<4;$i++){ echo $i; }.' suffix';

这是不可能的:

echo 'Prefix ';
for($i=0;$i<4;$i++)
{
   echo $i;
}
echo ' suffix';

因为我想使用 file_put_contents 保存页面,并且源代码具有 HTML 和 PHP 的组合。

我想得到:

$page =    <beginning_of_html_page_here>
    <php_code_here>
    <end_html_page_here>
file_put_contents(page.html, $page);

您可以使用字符串串联。使用点.连接到字符串,'a'.'b'将给出'ab'$a .= 'c'会将'c'附加到$a变量中。

// Create the string
$string = 'Prefix ';
for($i=0;$i<4;$i++)
{
   // Append the numbers to the string
   $string .= $i;
}
// Append the suffix to the string
$string .= ' suffix';
// Display the string
echo $string;

结果是:

前缀 0123 后缀

在代码键盘上演示。


关于你的问题结束,你可以使用这个逻辑:

$page = '<beginning_of_html_page_here>';
// Append things to your string with PHP
$page .= 'something'
$page .= '<end_html_page_here>';

关于您的第一个代码块,也可以通过使用两个函数来完成:range()生成数字数组和implode()连接数组的项目:

<?php
// Create the string
$string = 'Prefix '.implode('', range(0, 3)).' suffix';
echo $string;