How to Truncate Text in PHP without Third-party Library

Learn how you can easily truncate and shorten a text in PHP.

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:

  • 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

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:

<?php
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

// ๐Ÿ‘‡ use substr to get the first 20 characters
$truncated_text = substr($text, 0, 20);

print $truncated_text; // Lorem ipsum dolor si

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:

<?php
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

// ๐Ÿ‘‡ use substr to get the first 20 characters
$truncated_text = substr($text, 0, 20);

// ๐Ÿ‘‡ add ellipsis to the text
$truncated_text .= "...";

print $truncated_text; // Lorem ipsum dolor si...

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:

<?php
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

// ๐Ÿ‘‡ use substr to get the first 20 characters
$truncated_text = substr($text, 0, 20);

// ๐Ÿ‘‡ find the last space character index
$last_space = strrpos($truncated_text, " ");

// ๐Ÿ‘‡ truncate the text again, to the last space character
$truncated_text = substr($truncated_text, 0, $last_space);

// ๐Ÿ‘‡ add ellipsis to the text
$truncated_text .= "...";

print $truncated_text; // Lorem ipsum dolor...

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:

/**
 * A function to truncate a text
 *
 *
 * @param string $text The text to truncate
 * @param int $length Optional. The length of the new text.
 * @return string a new truncated text.
 */
function truncate(string $text, int $length = 20): string {
    if (strlen($text) <= $length) {
        return $text;
    }
    $text = substr($text, 0, $length);
    $text = substr($text, 0, strrpos($text, " "));
    $text .= "...";
    return $text;
}

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:

<?php

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

print truncate($text); // Lorem ipsum dolor...
print truncate($text, 25); // Lorem ipsum dolor sit...

Feel free to use the truncate() function in your project.

Now youโ€™ve learned how to truncate a text using PHP. Easy, right? ๐Ÿ˜‰

Original article source at: https://sebhastian.com/

#php #text 

What is GEEK

Buddha Community

How to Truncate Text in PHP without Third-party Library

Navigating Between DOM Nodes in JavaScript

In the previous chapters you've learnt how to select individual elements on a web page. But there are many occasions where you need to access a child, parent or ancestor element. See the JavaScript DOM nodes chapter to understand the logical relationships between the nodes in a DOM tree.

DOM node provides several properties and methods that allow you to navigate or traverse through the tree structure of the DOM and make changes very easily. In the following section we will learn how to navigate up, down, and sideways in the DOM tree using JavaScript.

Accessing the Child Nodes

You can use the firstChild and lastChild properties of the DOM node to access the first and last direct child node of a node, respectively. If the node doesn't have any child element, it returns null.

Example

<div id="main">
    <h1 id="title">My Heading</h1>
    <p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");
console.log(main.firstChild.nodeName); // Prints: #text

var hint = document.getElementById("hint");
console.log(hint.firstChild.nodeName); // Prints: SPAN
</script>

Note: The nodeName is a read-only property that returns the name of the current node as a string. For example, it returns the tag name for element node, #text for text node, #comment for comment node, #document for document node, and so on.

If you notice the above example, the nodeName of the first-child node of the main DIV element returns #text instead of H1. Because, whitespace such as spaces, tabs, newlines, etc. are valid characters and they form #text nodes and become a part of the DOM tree. Therefore, since the <div> tag contains a newline before the <h1> tag, so it will create a #text node.

To avoid the issue with firstChild and lastChild returning #text or #comment nodes, you could alternatively use the firstElementChild and lastElementChild properties to return only the first and last element node, respectively. But, it will not work in IE 9 and earlier.

Example

<div id="main">
    <h1 id="title">My Heading</h1>
    <p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");
alert(main.firstElementChild.nodeName); // Outputs: H1
main.firstElementChild.style.color = "red";

var hint = document.getElementById("hint");
alert(hint.firstElementChild.nodeName); // Outputs: SPAN
hint.firstElementChild.style.color = "blue";
</script>

Similarly, you can use the childNodes property to access all child nodes of a given element, where the first child node is assigned index 0. Here's an example:

Example

<div id="main">
    <h1 id="title">My Heading</h1>
    <p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");

// First check that the element has child nodes 
if(main.hasChildNodes()) {
    var nodes = main.childNodes;
    
    // Loop through node list and display node name
    for(var i = 0; i < nodes.length; i++) {
        alert(nodes[i].nodeName);
    }
}
</script>

The childNodes returns all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use children property instead.

Example

<div id="main">
    <h1 id="title">My Heading</h1>
    <p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");

// First check that the element has child nodes 
if(main.hasChildNodes()) {
    var nodes = main.children;
    
    // Loop through node list and display node name
    for(var i = 0; i < nodes.length; i++) {
        alert(nodes[i].nodeName);
    }
}
</script>

#javascript 

How to Truncate Text in PHP without Third-party Library

Learn how you can easily truncate and shorten a text in PHP.

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:

  • 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

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:

<?php
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

// ๐Ÿ‘‡ use substr to get the first 20 characters
$truncated_text = substr($text, 0, 20);

print $truncated_text; // Lorem ipsum dolor si

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:

<?php
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

// ๐Ÿ‘‡ use substr to get the first 20 characters
$truncated_text = substr($text, 0, 20);

// ๐Ÿ‘‡ add ellipsis to the text
$truncated_text .= "...";

print $truncated_text; // Lorem ipsum dolor si...

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:

<?php
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

// ๐Ÿ‘‡ use substr to get the first 20 characters
$truncated_text = substr($text, 0, 20);

// ๐Ÿ‘‡ find the last space character index
$last_space = strrpos($truncated_text, " ");

// ๐Ÿ‘‡ truncate the text again, to the last space character
$truncated_text = substr($truncated_text, 0, $last_space);

// ๐Ÿ‘‡ add ellipsis to the text
$truncated_text .= "...";

print $truncated_text; // Lorem ipsum dolor...

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:

/**
 * A function to truncate a text
 *
 *
 * @param string $text The text to truncate
 * @param int $length Optional. The length of the new text.
 * @return string a new truncated text.
 */
function truncate(string $text, int $length = 20): string {
    if (strlen($text) <= $length) {
        return $text;
    }
    $text = substr($text, 0, $length);
    $text = substr($text, 0, strrpos($text, " "));
    $text .= "...";
    return $text;
}

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:

<?php

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

print truncate($text); // Lorem ipsum dolor...
print truncate($text, 25); // Lorem ipsum dolor sit...

Feel free to use the truncate() function in your project.

Now youโ€™ve learned how to truncate a text using PHP. Easy, right? ๐Ÿ˜‰

Original article source at: https://sebhastian.com/

#php #text 

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website?

HourlyDeveloper.io has always been an industry leader for companies and business owners looking to hire PHP web developer. By choosing to Hire PHP Developer from our company, you can always expect the best results. Our PHP services and solutions are always flexible which means that no matter the nature of your project, you can always count on us for getting the best PHP expertise.

Consult with our experts: https://bit.ly/3aEGxPy

#hire php developer #php developer #php development company #php development services #php development #php

Hire PHP Developer - Best PHP Web Frameworks for Web Development

A framework that can drastically cut down the requirement to write original code to develop the web apps as per your requirement is PHP Framework. PHP frameworks offer code libraries for commonly used functions to reduce the development time.

Want to use PHP Web Frameworks for your web applications?

WebClues Infotech offers a service to hire dedicated PHP developers for all of the below-mentioned frameworks

  • Laravel Developer
  • Codeigniter Developer
  • Yii Developer
  • Zend Developer
  • Cake PHP Developer
  • Core PHP Developer

Not sure which framework to use for your PHP web application?

Contact us

Schedule Interview with PHP Developer https://bit.ly/3dsTWf0

Email: sales@webcluesinfotech.com

#hire php developer #hire php web developers #hire php developer in 2021 #hire php developers & dedicated php programmers #hire php developers india #hire and outsource freelance php developers

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers?

Hire Dedicated PHP Developer, who can convert your idea to reality, within the stipulated time frame. HourlyDeveloper.io expertise & experience as the top PHP development company put us above our competitors, in many ways. We have some of the top PHP developers in the industry, which can create anything you can imagine, that too, at the most competitive prices.

Consult with our experts:- https://bit.ly/2NpKnB8

#hire dedicated php developer #php developers #php development company #php development services #php development #php developer