(x)자 뒤에 텍스트를 자르다
이것은 워드프레스 형식입니다(그것이 차이를 만드는지는 확실하지 않습니다).
이 php 비트는 게시 제목을 출력합니다.
<?php echo $data['nameofpost']; ?>
최대 100자까지 사용할 수 있는 단순한 텍스트입니다.제가 원하는 것은 출력되는 문자가 '...'을 표시하기 위해 20자를 넘거나 아예 아무것도 표시되지 않는 경우입니다.
감사해요.
strlen으로 문자열 길이를 확인한 후 substren을 사용합니다.
$string = "This is a large text for demonstrations purposes";
if(strlen($string) > 20) $string = substr($string, 0, 20).'...';
echo $string;
출력
"This is a large text..."
단어 끝에 줄을 끊는 또 다른 방법은 정규식을 사용하는 것입니다.이 문자는 100자로 끊기거나 100자 뒤에 가장 가까운 단어 구분으로 설정됩니다.
function firstXChars($string, $chars = 100)
{
preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches);
return $matches[0];
}
<?php
function abbreviate($text, $max) {
if (strlen($text)<=$max)
return $text;
return substr($text, 0, $max-3).'...';
}
?>
<?php echo htmlspecialchars(abbreviate($data['nameofpost'], 20)); ?>
일반적인 개선사항은 단어 끝에 문자열을 잘라내는 것입니다.
if (strlen($text)<=$max)
return $text;
$ix= strrpos($text, ' ', $max-2);
if ($ix===FALSE)
$text= substr($text, 0, $max-3);
else
$text= substr($text, 0, $ix);
return $text.'...';
UTF-8 스트링을 사용하는 경우mb_ 문자열 ops의 멀티바이트 버전을 사용하여 문자를 보다 적절하게 카운트합니다.
테마 파일에서 다음과 같은 것을 사용해 보십시오.<div class="teaser-text"><?php the_content_limit(100, ''); ?></div>
함수에 있습니다.php 파일, 사용
function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '')
{
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$content = strip_tags($content);
if (strlen($_GET['p']) > 0)
{
echo "<div>";
echo $content;
echo "</div>";
}
else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char )))
{
$content = substr($content, 0, $espacio);
$content = $content;
echo "<div>";
echo $content;
echo "...";
echo "</div>";
}
else {
echo "<div>";
echo $content;
echo "</div>";
}
}
행운을 빈다:)
if(count($data['nameofpost']) > 20)
{
echo(substr($data['nameofpost'], 0, 17)."...");
}
위해서$data['nameofpost']20자를 초과하면 처음 17+3개의 도트가 출력됩니다.....
언급URL : https://stackoverflow.com/questions/2717181/cut-text-after-x-amount-of-characters
'programing' 카테고리의 다른 글
| JSON 문자 부호화 (0) | 2023.03.10 |
|---|---|
| Embeddable과 EmbeddedId 사이의 JPA 매핑 @ManyToOne (0) | 2023.03.10 |
| AJAX를 사용하여 PHP 파일에서 응답 가져오기 (0) | 2023.03.05 |
| MongoDB에서 컬렉션 이름을 변경하려면 어떻게 해야 합니까? (0) | 2023.03.05 |
| 대응 16: 경고: 일치하는 서버 HTML이 있어야 합니다.대응 16: 경고: 일치하는 서버 HTML이 있어야 합니다.에 (0) | 2023.03.05 |