php替换字符串中间字符为省略号的方法_PHP教程
php替换字符串中间字符为省略号的方法
本文实例讲述了php替换字符串中间字符为省略号的方法。分享给大家供大家参考。具体分析如下:
对于一个长字符串,如果你只希望用户看到头尾的部分内容,隐藏掉中间内容,你可以使用这个php函数,他可以指定要隐藏掉的中间字符串的数量
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/** * Reduce a string by the middle, keeps whole words together * * @param string $string * @param int $max (default 50) * @param string $replacement (default [...]) * @return string * @author david at ethinkn dot com * @author loic at xhtml dot ne * @author arne dot hartherz at gmx dot net */ function strMiddleReduceWordSensitive($string,$max=50,$rep='[...]'){ $strlen = strlen($string); if ($strlen return $string; $lengthtokeep = $max - strlen($rep); $start = 0; $end = 0; if (($lengthtokeep % 2) == 0) { $start = $lengthtokeep / 2; $end = $start; } else { $start = intval($lengthtokeep / 2); $end = $start + 1; } $i = $start; $tmp_string = $string; while ($i if (isset($tmp_string[$i]) and $tmp_string[$i] == ' ') { $tmp_string = substr($tmp_string, 0, $i) . $rep; $return = $tmp_string; } $i++; } $i = $end; $tmp_string = strrev ($string); while ($i if (isset($tmp_string[$i]) and $tmp_string[$i] == ' ') { $tmp_string = substr($tmp_string, 0, $i); $return .= strrev ($tmp_string); } $i++; } return $return; return substr($string, 0, $start).$rep.substr($string, - $end); } |
演示范例:
?
1 2 3 4 5 6 |
// example: $text = 'This is a very long test sentence, bla foo bar nothing'; print strMiddleReduceWordSensitive ($text, 30) . "\n"; // Returns: This is a very[...]foo bar nothing (~ 30 chrs) print strMiddleReduceWordSensitive ($text, 30, '...') . "\n"; // Returns: This is a very...foo bar nothing (~ 30 chrs) |
希望本文所述对大家的php程序设计有所帮助。