- PHP: Truncating Text
- Limiting or Truncating strings using PHP
- Truncation at sentence breaks
- Truncation at word breaks
- Truncating to a maximum length
- Truncating by words
- Restoring tags in truncated HTML
- Working Example
- References
- Related Articles — Text Manipulation
- How to truncate text in PHP without third-party library
- Step #1 — Use the substr() function to truncate the text
- Step #2 — Add ellipsis to the truncated text
- Step #3 — Truncate text at the last complete word
- Step #4 — Create a custom function to truncate texts
- Take your skills to the next level ⚡️
- About
- Search
- Tags
- ftruncate
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 5 notes
PHP: Truncating Text
A common problem when creating dynamic web pages (where content is sourced from a database, content management system or external source such as an RSS feed) is that the input text can be too long and cause the page layout to ‘break’.
One solution is to truncate the text so that it fits on the page. This sounds simple, but often the results aren’t as expected due to words and sentences being cut off at inappropriate points.
Limiting or Truncating strings using PHP
Here’s a simple function that avoids the usual pitfalls and offers some flexibility in formatting:
For the examples below we use the following paragraph consisting of four sentences of varying length:
$description = «The World Wide Web. When your average person on the street refers to the Internet, they’re usually thinking of the World Wide Web. The Web is basically a series of documents shared with the world written in a coding language called Hyper Text Markup Language or HTML. When you see a web page, like this one, you downloaded a document from another computer which has been set up as a Web Server.»;
Truncation at sentence breaks
The default action is to break on the first «.» after $limit characters and then pad with «. «. That means that the output will always be longer than $limit characters, but only as far as the next $break character. Further down the page you can find a function that returns a string that is always shorter than $limit.
$shortdesc = myTruncate($description, 300); echo «
$shortdesc
«;
The World Wide Web. When your average person on the street refers to the Internet, they’re usually thinking of the World Wide Web. The Web is basically a series of documents shared with the world written in a coding language called Hyper Text Markup Language or HTML. When you see a web page, like this one, you downloaded a document from another computer which has been set up as a Web Server. (not truncated)
$shortdesc = myTruncate($description, 200); echo «
$shortdesc
«;
The World Wide Web. When your average person on the street refers to the Internet, they’re usually thinking of the World Wide Web. The Web is basically a series of documents shared with the world written in a coding language called Hyper Text Markup Language or HTML.
$shortdesc = myTruncate($description, 100); echo «
$shortdesc
«;
The World Wide Web. When your average person on the street refers to the Internet, they’re usually thinking of the World Wide Web.
Truncation at word breaks
If your text consists of long sentences or you need precise control over the length then breaking on a space might be better. Some clarity is lost as the sentences are broken up, but at least the words remain intact.
$shortdesc = myTruncate($description, 300, » «); echo «
$shortdesc
«;
The World Wide Web. When your average person on the street refers to the Internet, they’re usually thinking of the World Wide Web. The Web is basically a series of documents shared with the world written in a coding language called Hyper Text Markup Language or HTML. When you see a web page, like this.
$shortdesc = myTruncate($description, 200, » «); echo «
$shortdesc
«;
The World Wide Web. When your average person on the street refers to the Internet, they’re usually thinking of the World Wide Web. The Web is basically a series of documents shared with the world written.
$shortdesc = myTruncate($description, 100, » «); echo «
$shortdesc
«;
The World Wide Web. When your average person on the street refers to the Internet, they’re usually thinking.
You’ll notice that the final text length is now closer to $limit characters, which makes sense as there are a lot more spaces in the normal text than periods.
Truncating to a maximum length
As noted previously, the function presented above will always return a string slightly longer than $limit characters, up to the next $break character. For those with stricter requirements, here’s an alternative function that will truncate text to the $break character before rather than after $limit:
Note that the default value for $break has changed to the space character. Using the «.» character as the breakpoint is now dangerous as there might only be one or two sentences in your text and you could end up with very few words left over.
Here you can see the output of this new function:
$shortdesc = myTruncate2($description, 300); echo «
$shortdesc
«;
The World Wide Web. When your average person on the street refers to the Internet, they’re usually thinking of the World Wide Web. The Web is basically a series of documents shared with the world written in a coding language called Hyper Text Markup Language or HTML.
$shortdesc = myTruncate2($description, 200); echo «
$shortdesc
«;
The World Wide Web. When your average person on the street refers to the Internet, they’re usually thinking of the World Wide Web.
$shortdesc = myTruncate2($description, 100); echo «
$shortdesc
«;
Truncating by words
If you simply want to truncate text to a certain number of words, then you don’t need any fancy functions, the code below will do the trick:
In other words, match up to 10 occurences of ‘one or more non-space characters followed by zero or more whitespace characters’:
The World Wide Web. When your average person on the (10 words)
For more information on trucating text, wrapping text to fit in a column, or splitting content evenly over two or more columns, see the related article on Word Wrapping.
An alternative solution has been provided by Bakaburg (see Feedback). Here is the same solution packaged into a function:
Usage should be fairly straight-forward:
The World Wide Web. When your average person on the.
Sure enough, we’re left with just the first 10 words of the text. Note that we’ve set the default delimiters for strtok to a space or line break. You can add other characters to this set as required, but not regular expressions as in the previous solution.
Restoring tags in truncated HTML
A lot of people have asked questions about how to deal with HTML tags in truncated text. Obviously the simplest approach is to remove any tags from the string to be truncated, but that’s not always good enough for real world applications where formatting is important.
This function accepts a string that contains HTML tags and will attempt to automatically close any tags that have been left open. There is an assumption here that the HTML was valid before it was truncated, so all tags were opened and closed in a valid order:
Please Note: This function is experimental so please use it with caution and give feedback using the Feedback link at the bottom of the page. If you’ve found a case where it doesn’t work, please provide an example so we can check it out.
Neither the truncation script nor the above function for restoring HTML tags is designed to handle text that contains image tags, or hyperlinks. They are designed simply for truncating plain text and HTML tags without any attributes. For a more comprehensive solution see the links below.
Working Example
You can use the form below to see how the truncate function (myTruncate) works — with the extra option of closing any open HTML tags (the restoreTags function).
References
Related Articles — Text Manipulation
- HTML Forcing INPUT text to uppercase
- JavaScript HTML content that expands on click
- JavaScript Collapsible containers with rotation support
- PHP Truncating Text
- PHP Word Wrapping
How to truncate text in PHP without third-party library
Having a long text as your website content can be a problem because it can break your web page layout.
To truncate (or cut short) a long text using PHP, you need to:
This tutorial will help you learn how to do the steps above. Let’s begin.
Step #1 — Use the substr() function to truncate the text
The substr() function is used to extract a part of the string.
This function can be used to truncate a text as shown below:
In the example above, the function is used to get the string from index 0 to 20 .
Step #2 — Add ellipsis to the truncated text
After you truncate the text, add the ellipsis to let readers know that you omit a portion of the text:
Finally, you see that the truncation leaves an incomplete word. You can make the truncation clean by cutting the text at the last space character.
Step #3 — Truncate text at the last complete word
You can find the last occurrence of space character using the strrpos() function:
Now the truncation leaves a complete word at the truncation point.
Step #4 — Create a custom function to truncate texts
And that’s all you need to truncate a text using PHP. You can create a custom function to store the code as follows:
The function above also allows you to specify the length of the truncated text.
It defaults to 20 but you can choose any length you want.
Now anytime you need to truncate a text, you just call the truncate() function:
Feel free to use the truncate() function in your project.
Now you’ve learned how to truncate a text using PHP. Easy, right? 😉
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
ftruncate
Принимает файловый указатель stream и урезает соответствующий файл до размера size .
Список параметров
Замечание:
stream должен быть открыт для записи.
Размер файла, до которого он будет обрезан.
Замечание:
Если size больше текущего размера файла, то файл будет дополнен нулевыми байтами.
Если size меньше текущего размера файла, то файл будет обрезан до этого размера.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Примеры
Пример #1 Пример обрезания файла
$handle = fopen ( $filename , ‘r+’ );
ftruncate ( $handle , rand ( 1 , filesize ( $filename )));
rewind ( $handle );
echo fread ( $handle , filesize ( $filename ));
fclose ( $handle );
?>
Примечания
Замечание:
Файловый указатель не меняется.
Смотрите также
User Contributed Notes 5 notes
If you want to empty a file of it’s contents bare in mind that opening a file in w mode truncates the file automatically, so instead of doing.
$fp = fopen ( «/tmp/file.txt» , «r+» );
ftruncate ( $fp , 0 );
fclose ( $fp );
?>
You can just do.
$fp = fopen ( «/tmp/file.txt» , «w» );
fclose ( $fp );
?>
I didnt expect that I can write in the middle of nowhere. I thought that I would write at the beginning of the file but the first 4 bytes were filled automatically with NULLs followed by «56»:
$str1 = 1234 ;
$str2 = 56 ;
$datei = «test.txt» ;
$dh = fopen ( $datei , «w» );
fwrite ( $dh , $str1 );
fclose ( $dh );
$dh = fopen ( $datei , «r+» );
echo «content: » . fread ( $dh , filesize ( $datei )). «
» ;
echo «pointer after fread at: » . ftell ( $dh ). «
» ;
ftruncate ( $dh , 0 );
echo «pointer after truncate at: » . ftell ( $dh ). «
» ;
fwrite ( $dh , $str2 );
echo «pointer after fwrite at: » . ftell ( $dh ). «
» ;
rewind ( $dh );
echo «pointer after rewind at: » . ftell ( $dh ). «
» ;
$str = fread ( $dh , 6 );
echo «content: $str
in ASCII: » ;
for( $i = 0 ; $i < 6 ; $i ++)
echo ord ( $str < $i >). «-» ;
fclose ( $dh );
/*
OUTPUT:
content: 1234
pointer after fread at: 4
pointer after truncate at: 4
pointer after fwrite at: 6
pointer after rewind at: 0
content: 56
in ASCII: 0-0-0-0-53-54
*/
?>
So not only ftruncate is filling an empty file up with NULLs as in the note before. Fread is filling leading space with NULLs too.
If you want to ftruncate but keep the end:
function ftruncatestart ( $filename , $maxfilesize ) $size = filesize ( $filename );
if ( $size < $maxfilesize * 1.0 ) return;
$maxfilesize = $maxfilesize * 0.5 ; //we don’t want to do it too often.
$fh = fopen ( $filename , «r+» );
$start = ftell ( $fh );
fseek ( $fh ,- $maxfilesize , SEEK_END );
$drop = fgets ( $fh );
$offset = ftell ( $fh );
for ( $x = 0 ; $x < $maxfilesize ; $x ++)fseek ( $fh , $x + $offset );
$c = fgetc ( $fh );
fseek ( $fh , $x );
fwrite ( $fh , $c );
>
ftruncate ( $fh , $maxfilesize — strlen ( $drop ));
fclose ( $fh );
>
?>
It will not just cut it but search for a newline so you avoid corrupting your csv or logfiles. But I don’t know if you will stress the reading head of your drive. 😉
The problem that rc at opelgt dot org mentioned seems completely logical.
When pointer is at offset 4 and you truncate file, the pointer is still at offset 4.
So when you write(), the first 4 bytes are filled with null byte by Operating System — There is nothing wrong by PHP. And it’s filled with null byte, because there is data on disk and that needs to be cleared with zero bits.
Even though this is a Operating System’s gotcha, to avoid data corruption, PHP Docs should mention it clearly. Also it would be nice if PHP automatically sets the pointer’s offset to SEEK_END after truncating to an smaller size to fool-proof it.