Skip to content

Instantly share code, notes, and snippets.

@axelarge
Last active October 7, 2015 04:17
Show Gist options
  • Save axelarge/3104082 to your computer and use it in GitHub Desktop.
Save axelarge/3104082 to your computer and use it in GitHub Desktop.
<?php
/**
* piegriež tekstu līdz noteiktam garumam
*
* @param string $str - Piegriežamais teksts
* @param int $maxLen - Maksimālais garums
* @param array $options - papildus opcijas
* - string omission => teksts, ko pieliek, ja nogriež (default: '...')
* - char separator => pēc kā atdalīt tekstu (default: null)
* - bool abbreviate => vai piegrieztais teksts jāievieto iekš <abbr> taga (default: false)
*
* @return string
*/
public function truncate($str, $maxLen = 0, $options = array()){
$options = array_merge(array(
'omission' => '...',
'separator' => null,
'abbreviate' => false,
), $options);
if(($strLen = mb_strlen($str)) > $maxLen){
$originalStr = $str;
$lengthWithOmission = $maxLen - mb_strlen(strip_tags($options['omission']));
$stop = ($options['separator'] && ($lastChar = mb_strrpos($str, $options['separator'], $lengthWithOmission - $strLen)))
? $lastChar
: $lengthWithOmission;
$str = mb_substr($str, 0, $stop) . $options['omission'];
if($options['abbreviate']){
$str = "<abbr title=\"{$originalStr}\">{$str}</abbr>";
}
}
return $str;
}
/**
* Pārvērš masīvu teikumā
* @param array $array
* @param array $options
* - separator => vārdu atdalītājs (default: ', ')
* - last_separator => pēdējo divu vārdu atdalītājs (default: ' un ' pareizajā valodā)
* @return string
*/
public function toSentence($array, $options = array()){
$options = array_merge(array(
'separator' => ', ',
'last_separator' => $this->view->lang('helpers.text.toSentence.lastSeparator'),
), $options);
switch(count($array)){
case 0: return '';
case 1: return $array[0];
default:
$last = array_pop($array);
return implode($options['separator'], $array) . $options['last_separator'] . $last;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment