1

使用explode我把文本分成几块,然后我们foreach在文本中寻找一些东西。

$pieces = explode(' ', $text);

foreach ($pieces as $piece) {
    Some Modification of the piece
}

我的问题是如何将这些部分重新组合在一起?所以我可以自动换行文本。有些像这样:

piece 1 + piece 2 + etc
4

6 回答 6

3

您将使用该implode()功能。

http://php.net/manual/en/function.implode.php

string implode ( string $glue , array $pieces )
string implode ( array $pieces )

编辑:可能是有史以来最具误导性的问题。

如果您尝试对正在构建的图像进行自动换行,也许您可​​以使用 float:left 样式将它们全部放在单独的 div 中。

于 2010-08-30T13:00:40.237 回答
2

首先,如果你想修改$piece循环内联中的每一个,你必须循环这些项目作为引用

foreach ($pieces as &$piece)

循环完成后,您可以使用以下命令再次生成单个字符串join()

$string = join(' ', $pieces);

(第一个参数join()是将各个部分粘合在一起的分隔符。使用最适合您的应用程序的任何内容。)

于 2010-08-30T13:02:57.707 回答
2

这是我的看法

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ornare tincidunt euismod. Pellentesque sodales elementum tortor posuere mollis. Curabitur in sem eu urna commodo vulputate.\nVivamus libero velit, auctor accumsan commodo vel, blandit nec turpis. Sed nec dui sit amet velit interdum tincidunt.";

// Break apart at new lines.
$pieces = explode("\n", $text);

// Use reference to be able to modify each piece.
foreach ($pieces as &$piece)
{
    $piece = wordwrap($piece, 80);
}

// Join the pieces together back into one line.
$wrapped_lines = join(' ', $pieces);

// Convert new lines \n to <br>.
$wrapped_lines = nl2br($wrapped_lines);
echo $wrapped_lines;

/* Output:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ornare tincidunt<br />
euismod. Pellentesque sodales elementum tortor posuere mollis. Curabitur in sem<br />
eu urna commodo vulputate. Vivamus libero velit, auctor accumsan commodo vel, blandit nec  turpis. Sed nec<br />
*/
于 2010-08-30T15:11:55.957 回答
1

到目前为止,所有答案都使它变得更加困难。为什么不在你修改它的时候把它重新组合起来呢?我想这就是你要找的。

$pieces = explode(' ', $text);

// text has already been passed to pieces so unset it
unset($text);

foreach ($pieces as $piece) {
    Some Modification of the piece
    // rebuild the text here
    $text .= {MODIFIED PIECE};
}

// print the new modified version
echo $text;
于 2010-08-30T15:10:32.990 回答
0

$pieces = implode(' ', $pieces);

于 2010-08-30T13:03:17.890 回答
0

问题很令人困惑,但是这样的工作是否可行:

$new = implode(' ', $pieces);
echo wordwrap($new, 120); // wordwrap 120 chars
于 2010-08-30T14:17:21.260 回答