我不知道以下几点:
我有返回的字符串,我想将前几个单词放在某个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
$ammountofwordsbeforespan = $count - 2;
echo '<p>'.$ammountofwordsbeforespan.'<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;
?>
演示: https : //3v4l.org/d3DYq
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句