php替换字符串中间字符为省略号的方法

yipeiwu_com6年前PHP代码库

本文实例讲述了php替换字符串中间字符为省略号的方法。分享给大家供大家参考。具体分析如下:

对于一个长字符串,如果你只希望用户看到头尾的部分内容,隐藏掉中间内容,你可以使用这个php函数,他可以指定要隐藏掉的中间字符串的数量

/**
 * 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 <= $max)
    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 < $strlen) {
    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 < $strlen) {
    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);
}

演示范例:

// 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程序设计有所帮助。

相关文章

回答PHPCHINA上的几个问题:URL映射

PHPCHINA服务器搬迁后,我就基本上上不去了,只能用代理,郁闷。但用代理居然不能发帖,回帖。做为版主,深感遗憾,今天用代理上去看到了几个帖子,顺便在这里回答下。  &nbs...

php使用str_shuffle()函数生成随机字符串的方法分析

本文实例讲述了php使用str_shuffle()函数生成随机字符串的方法。分享给大家供大家参考,具体如下: str_shuffle():随机打乱字符串的顺序。 可以通过str_shuf...

谈谈PHP连接Access数据库的注意事项

谈谈PHP连接Access数据库的注意事项

首先需要注意: 安装access 数据库的时候 需要安装与本机系统相互匹配的office版本,win7 64位的系统 ,那么Office也要是64位的 最好装 office2010。。。...

php下安装配置fckeditor编辑器的方法

一、PHP调用fckeditor方法。 二、JS调用fckeditor方法。 复制代码 代码如下: <?php require_once(PATH_PRE.”fckeditor.p...

php 处理上百万条的数据库如何提高处理查询速度

1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。 2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致...