问题
I have pulled a string out of a database it contains some html code as for example:
something about thing one<br>
now comes the second thing<br>
we're not done yet, here's another one<br>
and last but not least is the fourth one<br>
So I have four lines but when I print out the string I get an output like in the example above. What'd I'd like to do is manipulate every line so that I'd be able to do this:
<span>something about thing one</span>
<span>now comes the second thing</span>
<span>we're not done yet, here's another one</span>
<span>and last but not least is the fourth one</span>
I'd also like to have a counter for how many lines are there in a string (like for this one there are 4 lines) so I can set "odd" and "even" class for the span.
How do I do this?
回答1:
Simply use the explode() function with PHP_EOL
constant as delimiter:
$lines = explode(PHP_EOL, $original);
After you can iterate the returned array to parse lines, for example:
foreach ( $lines as $line )
{
echo '<span>'.$line.'</span>';
}
回答2:
Use explode
to split and I would prefer for
loop in these scenario instead of foreach
as the latter will return an empty span
tags in the end since it loops five times.
$arr = explode("<br>",$value);
for($i=0;$i<count($arr)-1; $i++){
echo "<span>".$arr[$i]."</span><br>";
}
To get the count you can use count
function:
echo count($arr)-1;
回答3:
You can explode the string with the delimiter and then use a foreach loop to get the answer you want.
$input = "omething about thing one<br>
now comes the second thing<br>
we're not done yet, here's another one<br>
and last but not least is the fourth one<br>";
//Explode the input string with br as delimiter
$data = explode ('<br>', $input );
//Filter $data array to remove any empty or null values
$data = array_filter($data);
//to get total data count
$count = count($data);
//now use loop to what you want
$i = 1;
foreach ( $data as $output)
{
//create class based on the loop
$class = $i % 2 == 0 ? 'even' : 'odd';
echo '<span class="'. $class .'">'. $output .'</span>';
$i++;
}
Hope this helps
来源:https://stackoverflow.com/questions/20150644/php-breaking-a-string-into-multiple-lines-and-manipulating-each-line-separately