用for循环组合两个字符串

时间:2016-02-26 22:28:12

标签: php

是否可以将两个字符串与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);

1 个答案:

答案 0 :(得分:0)

您可以使用string concatenation。使用点.加入字符串,'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后缀

Demo at Codepad

关于问题的结尾,您可以使用以下逻辑:

$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;
相关问题