开发者

PHP: combine text after explode

开发者 https://www.devze.com 2023-01-13 21:59 出处:网络
Using explode I broke up the text into pieces, then us the foreach to look for a few thing in the text.

Using explode I broke up the text into pieces, then us the foreach to look for a few thing in the text.

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

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

My questions so how can I put those pieces back together? So I can wordwrap the开发者_JS百科 text. Some like this:

piece 1 + piece 2 + etc


You would use the implode() function.

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

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

EDIT: Possibly the most misleading question ever.

If you're trying to word wrap the images you're constructing, perhaps you could put them all in individual div's in order with the float:left style.


Here's my take

$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 />
*/


First of all, if you want to modify each $piece in the loop inline, you have to loop over the items as references:

foreach ($pieces as &$piece)

When the loop is finished, you can produce a single string again by using join():

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

(The first parameter to join() is the separator that glues the pieces together. Use whatever fits your application best.)


All of the answers so far make it much more difficult than it is. Why not put it back together as you modify it? I think this is what you are looking for.

$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;


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


Question is quite confusing, but would something like this work:

$new = implode(' ', $pieces);
echo wordwrap($new, 120); // wordwrap 120 chars
0

精彩评论

暂无评论...
验证码 换一张
取 消