php函数,用于将普通行分隔成一个列表
我有一个变量$boo,它包含纯文本行,如(带有单数换行符): a b c 我想要一个函数将其格式化为项目符号列表。已提出以下内容,但无法获取任何输出:php函数,用于将普通行分隔成一个列表,php,line,Php,Line,我有一个变量$boo,它包含纯文本行,如(带有单数换行符): a b c 我想要一个函数将其格式化为项目符号列表。已提出以下内容,但无法获取任何输出: <?php function listformat ($list) { $listformat = explode("\n", $listformat); foreach ($listformat as $test => $line) { return "<li>".$line."</
<?php
function listformat ($list) {
$listformat = explode("\n", $listformat);
foreach ($listformat as $test => $line) {
return "<li>".$line."</li>";
};
};
?>
<ul>
<?php
listformat ($boo);
?>
</ul>
如果我用echo代替“return”并删除函数,它就可以工作。
return
结束函数并将语句发送回调用它的对象。所以,是的,回音是必要的
<?php
function listformat ($list) {
$listformat = explode("\n", $list);
foreach ($listformat as $line) {
echo "<li>".$line."</li>";
};
};
echo '<ul>';
listformat($my_list_var);
echo '</ul>';
您仍然可以保留该函数,但不是echo
或return
,而是使用局部变量构建HTML输出,并在末尾返回它:
<?php
function listformat ($list) {
$output = '<ul>';
$listformat = explode("\n", $list);
foreach ($listformat as $test => $line) {
$output .= "<li>".$line."</li>";
};
return $output.'</ul>';
};
?>
现在,您可以在任何地方使用您的函数,并响应返回值或执行任何您想要的操作:
<?php
echo(listformat($list));
?>
最简单的方法:
function ln2ul($string) {
return '<ul><li>' . str_replace("\n", '</li><li>', trim($string)) . '</li></ul>';
}
函数ln2ul($string){
返回“- ”。str_replace(“\n”),“
- ”,trim($string))。
”;
}
此函数不输出任何内容。您的函数未使用$list
。我也陷入了同样的陷阱,因为OP也有错误。你需要分解$list
好发现!证明我的命名惯例很糟糕。还必须使用echo而不是return;或者,如果我要使用return,就在函数中回显它,这无论如何都不应该在foreach循环中完成。