Limit text display in PHP

I want to limit the size of characters that appear, but I'm not getting it. Use o:

<? echo $row["catname"] ?>

It takes a text from phpMyAdmin and shows, only I want to limit the display of characters on the page, How do I?

 6
php
Author: brasofilo, 2014-07-19

4 answers

For cases where an indicator is required that string has been truncated, there is another option (which is almost unknown), which would be the function mb_strimwidth.

It seems that it was already made for this purpose:

mb_strimwidth("Hello World", 0, 10, "...");

Result

" Hello W..."

In this case, it should be noted that you have to add the number of the limiter added to the number of characters that will be the indication of the limitation.

For example:

 mb_strimwidth("Oi mundo", 0, 5, "...")

Displays:

" Oi..."

 15
Author: Wallace Maxters, 2016-12-06 11:08:45

Can use the substr(), this function has 3 parameters.

Substr (string, Start, End);

The string is the input it has, the start is the start position and the End is the end position.

In the case of the second or third parameters: being negative, it counts positions from the end. If it's positive, it counts from the start.

Examples:

echo substr("abcdef", 0, 2); // ab
echo substr("abcdef", 0, 4); // abcd
echo substr("abcdef", 0, -2); // abcd
 10
Author: Sergio, 2014-07-19 18:09:24

The most universal solution is this:

mb_substr ( string $str , int $start , [ int $length [, string $encoding ]] )

The function substr is limited to encodings single byte, and will have problems with strings with special characters in encodings like 'UTF-8' (for ISO it works fine). On the other hand, mb_substr counts by characters, not bytes, being more suitable for portable code.

Use with ISO-8859-1:

echo mb_substr( 'Acentuação faz diferença', 4, 10, 'ISO-8859-1' );

Use with UTF-8:

echo mb_substr( 'Acentuação faz diferença', 4, 10, 'UTF-8' );

Important : the last parameter can normally be omitted, to cases where the application is globally configured to use a specific encoding (which is desirable).

More details in the manual:

Http://php.net/manual/pt_BR/function.mb-substr.php

Related:

How to show only" x " characters in a div?

I cannot limit text with Japanese characters

 7
Author: Bacco, 2017-04-13 12:59:31

Do this:

<?php
echo substr($row["catname"], 0, 20);//Apenas os primeiros 20 caracteres
 5
Author: gpupo, 2014-07-19 20:30:54