-1

after asking this question on SO, I needed to prepare a custom PHP function to get a brief version of my string cause I couldn't find a direct answer / code on web.

requirements were:

  1. aware of multibyte language for characters like ş , ı , ğ encoded in UTF-8
  2. able to determine the allowed length (by using number of characters)
  3. after taking a portion of the long string, the word at the end of the string MUST be meaningful and concatenate ' ...' to the end of the portion
  4. must take into account the key strokes (characters) , not bytes

Readers shuld know that the code works however I am not an expert. I believe that it's possible to achieve the same aim with a much more efficient or deeper-thought coding. As you see also, code has no security concerns, it only manipulates the input string if it's longer than allowed.

regards

Community
  • 1
  • 1
Andre Chenier
  • 1,166
  • 2
  • 18
  • 37

1 Answers1

0
// PrintBrief   : Only introduction words (brief) are printed, multibyte safe
//                IMPORTANT: assumed that no tag has been used in input string
//                output's last word be a meaningful word, no need to worry about erroneous multibyte slicing
// $str         : string    input string to be written briefly
// $max_chars   : number    if string is longer than $max_chars, only first $max_chars will be the source string
// $encoding    : string    multibyte encoding
function PrintBrief ($str , $max_chars = ALLOWED_NUM_OF_CHARS, $encoding = "UTF-8")
{
    mb_regex_encoding($encoding);
    mb_internal_encoding($encoding);
    if ( mb_strlen($str , $encoding) > $max_chars )
    {
        $str = mb_substr($str , 0 , $max_chars , $encoding);
        $w = array();
        $w = mb_split(' ',$str);
        $k = array_pop($w);
        $k = trim(implode(' ', $w));
        $punc = array(';' , ',');
        for ( $i = 1 ; $i <= count($punc) ; $i++ )
        { $k = rtrim($k , $punc[$i] ); }
        return $k.' ...';

    }
    else
    {
        return $str;

    }
}

example usage:

$str = 'şğıöç İĞŞ ĞŞĞŞ Öİ ÇÇ Orta Amerika\'nın en büyük ülkesi Nikaragua\'nın başkenti Managua dün sabaha karşı büyük bir patlamayla sarsıldı. Olayın, şehre düşen ufak bir meteroit sonucu açılan krater çukurundan kaynaklandığı anlaşıldı. 1 milyon 200 bin kişinin yaşadığı ve bünyesinde ulsulararası bir havalimanının da olduğu şehre meteorit düşmesi sonucu, sürpriz bir şekilde can veya mal kaybı yaşanmadı ancak 12 metre çapında bir krater çukuru açıldı ve patlama neredeyse şehrin tamamında hissedildi.';

after calling with ALLOWED_NUM_OF_CHARS = 300 setting

echo PrintBrief ($str);

Output is :

şğıöç İĞŞ ĞŞĞŞ Öİ ÇÇ Orta Amerika'nın en büyük ülkesi Nikaragua'nın başkenti Managua dün sabaha karşı büyük bir patlamayla sarsıldı. Olayın, şehre düşen ufak bir meteroit sonucu açılan krater çukurundan kaynaklandığı anlaşıldı. 1 milyon 200 bin kişinin yaşadığı ve bünyesinde ulsulararası bir ...

Andre Chenier
  • 1,166
  • 2
  • 18
  • 37