将最后两个词放在不同的范围内 - PHP
Put last two words in different span - PHP
我无法弄清楚以下内容:我有返回的字符串,我想从中将前几个词放在某些 html 标记中,而不是最后两个,如下所示:
<p>This is a <span class="someclass">returned string</span></p>
我知道我可以将字符串分解成一个数组并使每个单词都成为一个迭代,但是我只能弄清楚如何将前两个单词放在不同的 html 标记中,我想要最后两个。每个字符串可以有不同数量的单词。
我正在考虑用数组计数做一些事情,比如:
$string = this is a returned string;
$words = explode(" ", $string);
$count = count($words); // $words in this case is 5
$amountofwordsbeforespan = $count - 2;
echo '<p>'.$amountofwordsbeforespan.'<span class="somethingtostyleit">'.SOMETHING THAT PUTS THE LAST TWO HERE.'</span></p>';
但我认为应该有更简单的方法。
有人知道完成此操作的最简洁方法是什么吗?
使用array_splice()
、
的另一种方式
<?php
$string = 'this is a returned string';
$words = explode(" ", $string );
$last_two_word = implode(' ',array_splice($words, -2 ));
$except_last_two = implode(' ', $words);
$expected = '<p>'.$except_last_two.' <span class="someclass">'.$last_two_word.'</span></p>';
echo $expected;
?>
我无法弄清楚以下内容:我有返回的字符串,我想从中将前几个词放在某些 html 标记中,而不是最后两个,如下所示:
<p>This is a <span class="someclass">returned string</span></p>
我知道我可以将字符串分解成一个数组并使每个单词都成为一个迭代,但是我只能弄清楚如何将前两个单词放在不同的 html 标记中,我想要最后两个。每个字符串可以有不同数量的单词。
我正在考虑用数组计数做一些事情,比如:
$string = this is a returned string;
$words = explode(" ", $string);
$count = count($words); // $words in this case is 5
$amountofwordsbeforespan = $count - 2;
echo '<p>'.$amountofwordsbeforespan.'<span class="somethingtostyleit">'.SOMETHING THAT PUTS THE LAST TWO HERE.'</span></p>';
但我认为应该有更简单的方法。
有人知道完成此操作的最简洁方法是什么吗?
使用array_splice()
、
<?php
$string = 'this is a returned string';
$words = explode(" ", $string );
$last_two_word = implode(' ',array_splice($words, -2 ));
$except_last_two = implode(' ', $words);
$expected = '<p>'.$except_last_two.' <span class="someclass">'.$last_two_word.'</span></p>';
echo $expected;
?>