我需要一种方法来计算PHP中单词(不是字符)的数量,并在HTML中启动一个<SPAN>
标记,将指定数字之后的剩余单词括起来。
一切似乎都工作得很好,但是我想在这里发布,因为这段代码是从2005年开始的,也许有一个更现代/有效的方式来处理我想要达到的目标?
<?php
$string = "One two three four five six seven eight nine ten.";
// the first number words to extract
$n = 3;
// extract the words
$words = explode(" ", $string);
// chop the words array down to the first n elements
$first = array_slice($words, 0, $n);
// chop the words array down to the retmaining elements
$last = array_slice($words, $n);
// glue the 3 elements back into a spaced sentence
$firstString = implode(" ", $first);
// glue the remaining elements back into a spaced sentence
$lastString = implode(" ", $last);
// display it
echo $firstString;
echo '<span style="font-weight:bold;"> '.$lastString.'</span>';
?>
您可以使用preg_split()
与正则表达式代替。这是这个答案的修改版本,使用了一个改进的正则表达式,它使用了一个正向后看:
function get_snippet($str, $wordCount) {
$arr = preg_split(
'/(?<='w)'b/',
$str,
$wordCount*2+1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
$first = implode('', array_slice($arr, 0, $wordCount));
$last = implode('', array_slice($arr, $wordCount));
return $first.'<span style="font-weight:bold;">'.$last.'</span>';
}
用法:
$string = "One two three four five six seven eight nine ten.";
echo get_snippet($string, 3);
输出:一二三四五六七八九十
让我们更加简单。试试这个
<?php
$string = "One two three four five six seven eight nine ten.";
// the first number words to extract
$n = 2;
// extract the words
$words = explode(" ", $string);
for($i=0; $i<=($n-1); $i++) {
$firstString[] = $words[$i]; // This will return one, two
}
for($i =$n; $i<count($words); $i++) {
$firstString[] = $words[$i]; // This will return three four five six seven eight nine ten
}
print_r($firstString);
print_r($firstString);
?>
演示
我从这里借用了代码:
https://stackoverflow.com/a/18589825/1578471/**
* Find the position of the Xth occurrence of a substring in a string
* @param $haystack
* @param $needle
* @param $number integer > 0
* @return int
*/
function strposX($haystack, $needle, $number){
if($number == '1'){
return strpos($haystack, $needle);
}elseif($number > '1'){
return strpos($haystack, $needle, strposX($haystack, $needle, $number - 1) + strlen($needle));
}else{
return error_log('Error: Value for parameter $number is out of range');
}
}
$string = "One two three four five six seven eight nine ten.";
$afterThreeWords = strposX($string, " ", 3);
echo substr($string, 0, $afterThreeWords); // first three words
这看起来不错,这里有另一种方法可以检查效率吗?我不知道哪个更快。我猜对于较长的字符串
,你的更快。$string = "This is some reasonably lengthed string";
$n = 3;
$pos = 0
for( $i = 0; $i< $n; $i++ ){
$pos = strpos($string, ' ', $pos + 1);
if( !$pos ){
break;
}
}
if( $pos ){
$firstString = substr($string, 0, $pos);
$lastString = substr($string, $pos + 1);
}else{
$firstString = $string;
$lastString = null;
}