Limit text display in PHP

2

I want to limit the size of characters that appear, but I can not. Use o:

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

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

    
asked by anonymous 19.07.2014 / 20:05

4 answers

6

You can use substr () , this function has 3 parameters.

  

substr (string, start, end);

The string is the input you have, the start is the starting position and the end is the final position.

In case of the second or third parameter: being negative, it counts positions from the end. If it is positive, count from the beginning.

Examples:

echo substr("abcdef", 0, 2); // ab
echo substr("abcdef", 0, 4); // abcd
echo substr("abcdef", 0, -2); // abcd
    
19.07.2014 / 20:09
5

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

It looks like it has already been made for this purpose:

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

Result

  

"Hello W ..."

In this case, you have to note that you have to add the limiter number added to the number of characters that will indicate the limitation.

For example:

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

Displays:

  

"Hi ..."

    
06.12.2016 / 12:08
5

The most universal solution is this:

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

The function substr is limited to single byte encodings, and will have problems with strings with special characters in encodings such as 'UTF-8' (for ISO works well). The mb_substr counts by characters, not , 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 usually be omitted, in cases where the application is globally configured to use a specific encoding (which is desirable).

More details in the manual:

  

link

Related:

  

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

  

I can not limit text with Japanese characters

    
06.12.2016 / 12:02
2

Do this:

<?php
echo substr($row["catname"], 0, 20);//Apenas os primeiros 20 caracteres
    
19.07.2014 / 22:30