Nice programing

PHP에서 문자열을 처음 20 개 단어로자를 수 있습니까?

nicepro 2020. 12. 9. 21:42
반응형

PHP에서 문자열을 처음 20 개 단어로자를 수 있습니까?


PHP에서 20 단어 이후에 문자열을 어떻게자를 수 있습니까?


function limit_text($text, $limit) {
      if (str_word_count($text, 0) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          $text = substr($text, 0, $pos[$limit]) . '...';
      }
      return $text;
    }

echo limit_text('Hello here is a long sentence blah blah blah blah blah hahahaha haha haaaaaa', 5);

출력 :

Hello here is a long ...

3숫자를 20아래 숫자 변경하여 처음 20 개 단어를 얻거나 매개 변수로 전달하십시오. 다음은 처음 3 개의 단어를 얻는 방법을 보여줍니다. (따라서 3to 20를 변경하여 기본값을 변경하십시오) :

function first3words($s, $limit=3) {
    return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s);   
}

var_dump(first3words("hello yes, world wah ha ha"));  # => "hello yes, world"
var_dump(first3words("hello yes,world wah ha ha"));   # => "hello yes,world"
var_dump(first3words("hello yes world wah ha ha"));   # => "hello yes world"
var_dump(first3words("hello yes world"));  # => "hello yes world"
var_dump(first3words("hello yes world.")); # => "hello yes world"
var_dump(first3words("hello yes"));  # => "hello yes"
var_dump(first3words("hello"));  # => "hello"
var_dump(first3words("a")); # => "a"
var_dump(first3words(""));  # => ""

가장 가까운 공간으로

대상 문자의 가장 가까운 선행 공백으로 자릅니다. 데모

  • $str 잘릴 문자열
  • $chars 제거 할 문자의 양은 다음으로 재정의 할 수 있습니다. $to_space
  • $to_space boolean$chars한계에 가까운 공간에서자를 지 여부

함수

function truncateString($str, $chars, $to_space, $replacement="...") {
   if($chars > strlen($str)) return $str;

   $str = substr($str, 0, $chars);
   $space_pos = strrpos($str, " ");
   if($to_space && $space_pos >= 0) 
       $str = substr($str, 0, strrpos($str, " "));

   return($str . $replacement);
}

견본

<?php

$str = "this is a string that is just some text for you to test with";

print(truncateString($str, 20, false) . "\n");
print(truncateString($str, 22, false) . "\n");
print(truncateString($str, 24, true) . "\n");
print(truncateString($str, 26, true, " :)") . "\n");
print(truncateString($str, 28, true, "--") . "\n");

?>

산출

this is a string tha...
this is a string that ...
this is a string that...
this is a string that is :)
this is a string that is--

사용이 폭발 () .

문서의 예.

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

explode에는 제한 기능이 있습니다. 그래서 당신은 다음과 같은 것을 할 수 있습니다.

$message = implode(" ", explode(" ", $long_message, 20));

정규식을 사용해보십시오.

20 단어 (또는 20 단어 경계)와 일치하는 것이 필요합니다.

그래서 (내 정규식은 끔찍하므로 정확하지 않은 경우 수정하십시오) :

/(\w+\b){20}/

그리고 여기 php에서 정규식의 몇 가지 예가 있습니다.


간단하고 완전한 기능을 갖춘 truncate () 메서드 :

function truncate($string, $width, $etc = ' ..')
{
    $wrapped = explode('$trun$', wordwrap($string, $width, '$trun$', false), 2);
    return $wrapped[0] . (isset($wrapped[1]) ? $etc : '');
}

내 자신이 만든 것이 아니라 이전 게시물을 수정 한 것입니다. 크레딧은 karim79로 이동합니다.

function limit_text($text, $limit) {
    $strings = $text;
      if (strlen($text) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          if(sizeof($pos) >$limit)
          {
            $text = substr($text, 0, $pos[$limit]) . '...';
          }
          return $text;
      }
      return $text;
    }

문자열을 (배열로) <space 로 분할 한 >다음 해당 배열의 처음 20 개 요소를 가져옵니다.


이것은 나에게 꽤 좋아 보인다 .

동적 웹 페이지를 만들 때 (콘텐츠가 데이터베이스, 콘텐츠 관리 시스템 또는 RSS 피드와 같은 외부 소스에서 제공되는) 일반적인 문제는 입력 텍스트가 너무 길어 페이지 레이아웃이 '중단'될 수 있다는 것입니다.

한 가지 해결책은 페이지에 맞도록 텍스트를 자르는 것입니다. 간단하게 들리지만 단어와 문장이 부적절한 지점에서 잘려 결과가 예상과 다른 경우가 많습니다.


트리플 도트 사용 :

function limitWords($text, $limit) {
    $word_arr = explode(" ", $text);

    if (count($word_arr) > $limit) {
        $words = implode(" ", array_slice($word_arr , 0, $limit) ) . ' ...';
        return $words;
    }

    return $text;
}

Laravel에서 코딩하면 use Illuminate\Support\Str

여기에 예가 있습니다

Str::words($category->publication->title, env('WORDS_COUNT_HOME'), '...')

도움이 되었기를 바랍니다.


이와 같은 것이 아마도 트릭을 할 수 있습니다.

<?php 
$words = implode(' ', array_slice(split($input, ' ', 21), 0, 20));

루프에서 PHP 토크 나이저 함수 strtok () 를 사용하십시오.

$token = strtok($string, " "); // we assume that words are separated by sapce or tab
$i = 0;
$first20Words = '';
while ($token !== false && $i < 20) {
    $first20Words .= $token;
    $token = strtok(" ");
    $i++;
}
echo $first20Words;

動靜 能量의 답변에 따라 :

function truncate_words($string,$words=20) {
 return preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
}

또는

function truncate_words_with_ellipsis($string,$words=20,$ellipsis=' ...') {
 $new = preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
 if($new != $string){
  return $new.$ellipsis;
 }else{
  return $string;
 }

}

아래 코드를 시도하십시오.

 $text  = implode(' ', array_slice(explode(' ', $text), 0, 32))
 echo $text;

다음은 내가 구현 한 것입니다.

function summaryMode($text, $limit, $link) {
    if (str_word_count($text, 0) > $limit) {
        $numwords = str_word_count($text, 2);
        $pos = array_keys($numwords);
        $text = substr($text, 0, $pos[$limit]).'... <a href="'.$link.'">Read More</a>';
    }
    return $text;
}

보시다시피 karim79의 답변을 기반으로 한 것이므로 변경해야 할 것은 if 문이 문자가 아닌 단어를 확인해야한다는 것입니다.

편의를 위해 주요 기능에 대한 링크도 추가했습니다. 지금까지 hsa는 완벽하게 작동했습니다. 원래 솔루션 제공 업체 덕분입니다.


내가 사용하는 것은 다음과 같습니다.

    $truncate = function( $str, $length ) {
        if( strlen( $str ) > $length && false !== strpos( $str, ' ' ) ) {
            $str = preg_split( '/ [^ ]*$/', substr( $str, 0, $length ));
            return htmlspecialchars($str[0]) . '&hellip;';
        } else {
            return htmlspecialchars($str);
        }
    };
    return $truncate( $myStr, 50 );

또 다른 해결책 :)

$aContent = explode(' ', $cContent);
$cContent = '';
$nCount = count($aContent);
for($nI = 0; ($nI < 20 && $nI < $nCount); $nI++) {
   $cContent .= $aContent[$nI] . ' ';
}
trim($cContent, ' ');
echo '<p>' . $cContent . '</p>';

This worked me for UNICODE (UTF8) sentences too:

function myUTF8truncate($string, $width){
    if (mb_str_word_count($string) > $width) {
        $string= preg_replace('/((\w+\W*|| [\p{L}]+\W*){'.($width-1).'}(\w+))(.*)/', '${1}', $string);
    }
    return $string;
}

To limit words, am using the following little code :

    $string = "hello world ! I love chocolate.";
    $explode = array_slice(explode(' ', $string), 0, 4);
    $implode = implode(" ",$explode);   
    echo $implode;

$implot will give : hello world ! I


function getShortString($string,$wordCount,$etc = true) 
{
     $expString = explode(' ',$string);
     $wordsInString = count($expString);
     if($wordsInString >= $wordCount )
     {
         $shortText = '';
         for($i=0; $i < $wordCount-1; $i++)
         {
             $shortText .= $expString[$i].' ';
         }
         return  $etc ? $shortText.='...' : $shortText; 
     }
     else return $string;
} 

Lets assume we have the string variables $string, $start, and $limit we can borrow 3 or 4 functions from PHP to achieve this. They are:

  • script_tags() PHP function to remove the unnecessary HTML and PHP tags (if there are any). This wont be necessary, if there are no HTML or PHP tags.
  • explode() to split the $string into an array
  • array_splice() to specify the number of words and where it'll start from. It'll be controlled by vallues assigned to our $start and $limit variables.
  • and finally, implode() to join the array elements into your truncated string..

    function truncateString($string, $start, $limit){
        $stripped_string =strip_tags($string); // if there are HTML or PHP tags
        $string_array =explode(' ',$stripped_string);
        $truncated_array = array_splice($string_array,$start,$limit);
        $truncated_string=implode(' ',$truncated_array);
    
        return $truncated_string;
    }
    

It's that simple..

I hope this was helpful.


I made my function:

function summery($text, $limit) {
    $words=preg_split('/\s+/', $text);
     $count=count(preg_split('/\s+/', $text));
      if ($count > $limit) {
          $text=NULL;
          for($i=0;$i<$limit;$i++)
              $text.=$words[$i].' ';
          $text.='...';
      }
      return $text;
    }

function limitText($string,$limit){
        if(strlen($string) > $limit){
                $string = substr($string, 0,$limit) . "...";
        }
        return $string;
}

this will return 20 words. I hope it will help


$text='some text';
$len=strlen($text);
    $limit=500;
// char
    if($len>$limit){
        $text=substr($text,0,$limit);
        $words=explode(" ", $text);
        $wcount=count($words);
        $ll=strlen($words[$wcount]);
        $text=substr($text,0,($limit-$ll+1)).'...';
    }

what about

chunk_split($str,20);

Entry in the PHP Manual


    function limit_word($start,$limit,$text){
            $limit=$limit-1;
            $stripped_string =strip_tags($text);
            $string_array =explode(' ',$stripped_string);
            if(count($string_array)>$limit){
            $truncated_array = array_splice($string_array,$start,$limit);
            $text=implode(' ',$truncated_array).'...';
            return($text);
            }
            else{return($text);}
    }

참고URL : https://stackoverflow.com/questions/965235/how-can-i-truncate-a-string-to-the-first-20-words-in-php

반응형