PHP 循环错误 - 只有部分循环被循环?
到目前为止,我和几个参加同一编程课程的朋友已经对此感到困惑了几个小时,希望这里有人可以提供帮助。 目的是获取一个 url 列表,按新行分割,为每个 URL 添加 [img] 和附加 [/ img],适合公告板。实际代码包含一个允许 [img] 和 [thumb] bbcode 的开关,但两者具有相同的效果。 它不是输出而是
[ img]1[/ img]
[ img]2[/ img]
输出
[ img]1
2[ /img]
对于任意数量的 URL 都会发生同样的情况。这是我正在使用的代码。
<?php
$url_f = (isset($_POST['text'])) ? $_POST['text'] : false;
$thumb = (isset($_POST['type'])) ? $_POST['type'] : false;
$urls = ($url_f) ? explode('\n',$url_f) : '';
?>
<textarea rows='20' cols='40' readonly='1'>
<?php
switch ($thumb){
case 'img':
for ($i = count($urls)-1; $i >= 0; $i--)
{
echo "[img]". $urls[$i] ."[/img]\n";
}
break;
default:
break;
case 'thumb':
for ($i = count($urls)-1; $i >= 0; $i--)
{
echo '[thumb]'. $urls[$i] ."[/thumb]\n";
}
break;
}
?>
</textarea>
Me and several friends taking the same programming course have been confused by this for hours so far, hopefully someone here can help.
The aim is to take a list of urls, split by new lines, prepend [ img] and append [/ img] for each URL, as suitable for a bulletin board. The actual code includes a switch to allow for both [ img] and [ thumb] bbcodes, but both have the same effect.
Instead of outputting
[ img]1[/ img]
[ img]2[/ img]
it outputs
[ img]1
2[ /img]
The same happens for any number of URLs. Here's the code I am using.
<?php
$url_f = (isset($_POST['text'])) ? $_POST['text'] : false;
$thumb = (isset($_POST['type'])) ? $_POST['type'] : false;
$urls = ($url_f) ? explode('\n',$url_f) : '';
?>
<textarea rows='20' cols='40' readonly='1'>
<?php
switch ($thumb){
case 'img':
for ($i = count($urls)-1; $i >= 0; $i--)
{
echo "[img]". $urls[$i] ."[/img]\n";
}
break;
default:
break;
case 'thumb':
for ($i = count($urls)-1; $i >= 0; $i--)
{
echo '[thumb]'. $urls[$i] ."[/thumb]\n";
}
break;
}
?>
</textarea>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
<罢工>
换行符共有三种不同类型:\r、\n 和 \r\n。我不做太多的网络开发,但不同的操作系统仍然可能会发送不同的换行符,因此您必须进行一些检查以找出要分割的字符。
在您的代码中,由于 \n 不起作用,换行符可能是 \r\n 或 \r。
编辑:单引号字符串文字可能是问题所在。
There are three different types of newlines: \r, \n, and \r\n. I don't do much web development, but different OSes will still probably send different newlines, so you'll have to do some checking to find out what character(s) to split with.
In your code, since \n isn't working, the newline is probably \r\n or \r.
Edit: The single quoted string literal may be the problem.
您的问题是
'\n' !== "\n"
。前者被处理为“反斜杠n”,而后者被处理为换行符(ASCII 0xA,bein LF)。请参阅双引号字符串了解更多信息。关于您的循环,您可能需要查看 foreach。
Your Problem is
'\n' !== "\n"
. The former is treated as "backslash n", while the latter is processed to the line feed character (ASCII 0xA, bein LF). See Double Quoted Strings for more info.Regarding your loop, you might want to look into foreach.