将字符串拆分为多列(标签感知)
尝试写这样的功能。它必须将文本分成多列,并且输出必须是有效的html,例如没有未打开的(!!!) 关闭标签和没有未关闭的标签。这是我的代码:
function convert2columns($content = '', $columns = 2) {
$result = array();
$content = closetags($content);
$bodytext = array("$content");
$text = implode(",", $bodytext);
$length = strlen($text);
$length = ceil($length / $columns);
$words = explode(" ", $text);
$c = count($words);
$l = 0;
for ($i = 1; $i <= $columns; $i++) {
$new_string = "";
for ($g = $l; $g <= $c; $g++) {
if (strlen($new_string) <= $length || $i == $columns) {
if (in_array(substr(@$words[$g], $length - 1, 1), array(' ', '.', '!', '?')))
$new_string .= @$words[$g] . " ";
else {
$split = substr(@$words[$g], 0, $length - 1);
$lastSpace = strrpos($split, ' ');
if ($lastSpace !== false) {
$split = substr($split, 0, $lastSpace);
}
if (in_array(substr($split, -1, 1), array(','))) {
$split = substr($split, 0, -1);
}
$new_string .= $split . " ";
}
} else {
$l = $g;
break;
}
}
$result[] = $new_string;
}
return $result;
}
有效,但是当尝试将一些文本分成两列时,我在第一列中得到未关闭的标签,在第二列中得到未打开的标签。如何解决这个问题?需要帮助!
Trying to write such function. It must divide text into multiple columns and the output must be valid html, e.g. no unopened(!!!) close tags and no unclosed tags. Here is my code:
function convert2columns($content = '', $columns = 2) {
$result = array();
$content = closetags($content);
$bodytext = array("$content");
$text = implode(",", $bodytext);
$length = strlen($text);
$length = ceil($length / $columns);
$words = explode(" ", $text);
$c = count($words);
$l = 0;
for ($i = 1; $i <= $columns; $i++) {
$new_string = "";
for ($g = $l; $g <= $c; $g++) {
if (strlen($new_string) <= $length || $i == $columns) {
if (in_array(substr(@$words[$g], $length - 1, 1), array(' ', '.', '!', '?')))
$new_string .= @$words[$g] . " ";
else {
$split = substr(@$words[$g], 0, $length - 1);
$lastSpace = strrpos($split, ' ');
if ($lastSpace !== false) {
$split = substr($split, 0, $lastSpace);
}
if (in_array(substr($split, -1, 1), array(','))) {
$split = substr($split, 0, -1);
}
$new_string .= $split . " ";
}
} else {
$l = $g;
break;
}
}
$result[] = $new_string;
}
return $result;
}
Works, but When trying to divide some text into 2 columns, I get unclosed tags in first column and unopened in second. How to fix this? Need help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我的解决方案。我想要一些能够识别段落、块引用、表格等的代码,因此第二列总是在所有标签关闭后开始。
Here's my solution. I wanted some code that would be aware of paragraphs, blockquotes, tables etc. so the second column always starts after all tags have been closed.