🇯🇵 日本語 | 🇺🇸 English | 🇪🇸 Español | 🇵🇹 Português | 🇹🇭 ไทย | 🇨🇳 中文

[PHP for Beginners] The Reusable Magic! How to Generate Excerpts with Functions

Have you ever wanted to display just a short, introductory part of each article on a blog's index page? An "excerpt" that tells readers "this is what the article is about" is very important for encouraging them to browse your site. However, creating excerpts manually every time you add an article is a lot of work, right?

This article introduces a magical tool in PHP called a function that solves this problem. Let's try creating our own handy "excerpt generation tool" as a PHP function that takes a long piece of text, cuts it to a specified character count, and appends "...read more" to the end. We'll also cover `htmlspecialchars()`, which is essential for security, so you'll get safe and practical code. It's copy-paste friendly even for beginners!

To get your PHP running (development environment), if you haven't set up XAMPP yet, please refer to [PHP for Beginners] A Complete Guide to Downloading and Installing XAMPP!. After installation, place your PHP file in the specified folder (like `htdocs`), and you're all set!

1. What is the Code-Organizing Magic "Function"?

First, what is a "function"? Simply put, it's like a "custom-made tool" where you bundle a specific process, give it a name, and can call it to use anytime.

For example, if you create a function for the series of steps "receive text, cut it to 100 characters, and add '...' to the end," then you only need to call that function whenever you need an excerpt. You don't have to write the same code over and over, which makes your entire codebase cleaner and easier to manage. This is the biggest advantage of functions.

The basic syntax is as follows:

<?php
function function_name(argument1, argument2, ...) {
  // Write the process you want to execute here

  return return_value; // Returns the result of the process
}
?>

It's easy to understand if you think of arguments as the "ingredients" you pass to the function, and the return value as the "finished product" the function gives back. Now, let's use this syntax to create our excerpt generation function.

2. In Practice! Let's Create a Function to Generate Excerpts

This is the main part of this article. We will create a function named `make_excerpt()` that you can give a long text and a character count to, and it will return a nicely shortened excerpt. The code below is a complete HTML example that you can copy and paste into a file to immediately see it work in your browser.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Excerpt Generation Tool</title>
    <style>
        body { font-family: sans-serif; line-height: 1.6; padding: 20px; }
        .original-text { background: #f4f7f6; border-left: 5px solid #ccc; padding: 10px; margin-bottom: 20px; }
        .excerpt { background: #e8f4f8; border-left: 5px solid #007bff; padding: 10px; }
    </style>
</head>
<body>

    <h1>Excerpt Generation Test</h1>

    <?php
    /**
     * Generates an excerpt.
     * @param string $text The original text.
     * @param int $length The character limit.
     * @return string The generated excerpt.
     */
    function make_excerpt(string $text, int $length): string {
        // Check the character count of the original text
        if (mb_strlen($text) > $length) {
            // Cut to the specified character count and append "...read more"
            return mb_substr($text, 0, $length) . '...read more';
        } else {
            // If the character count is less than the limit, return it as is
            return $text;
        }
    }

    // A long original text
    $long_text = 'This is a very long text. This article explains in detail how to use PHP functions to cut text to a specific character count and generate an excerpt. This is a practical technique useful for blog index pages and more.';

    // Call the function to generate a 50-character excerpt
    $excerpt_text = make_excerpt($long_text, 50);
    ?>

    <h2>Original Text</h2>
    <div class="original-text">
        <?php echo $long_text; ?>
    </div>

    <h2>Generated Excerpt (50-character limit)</h2>
    <div class="excerpt">
        <?php echo $excerpt_text; ?>
    </div>

</body>
</html>

The key points in this code are `mb_strlen()` and `mb_substr()`. To correctly handle multi-byte characters like Japanese, you need to use functions that start with `mb_` instead of `strlen()` or `substr()`. This prevents garbled text and ensures you can cut the text at the intended character count.

3. Important! Secure Display with htmlspecialchars

When displaying text on a web page, one thing you must never forget is security. If the text to be displayed contains HTML tags like `<script>`, displaying it as is could cause unintended behavior (a Cross-Site Scripting attack).

This is where the `htmlspecialchars()` function comes in. This function converts characters that have special meaning in HTML (e.g., `<`, `>`, `&`, `"`) into harmless strings (e.g., `&lt;`, `&gt;`, `&amp;`, `&quot;`).

Let's improve our excerpt generation function by incorporating this process to make it more secure.

<?php
/**
 * An improved function to generate a safe excerpt.
 */
function make_safe_excerpt(string $text, int $length): string {
    // 1. First, escape with htmlspecialchars
    $safe_text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');

    // 2. Perform the character count check and cut on the escaped text
    if (mb_strlen($safe_text) > $length) {
        return mb_substr($safe_text, 0, $length) . '...read more';
    } else {
        return $safe_text;
    }
}

// Text that might contain HTML tags
$dangerous_text = '<strong>Emphasized</strong> text and malicious code like <script>alert("danger!");</script>.';

// Use the improved function to generate a safe excerpt
$safe_excerpt = make_safe_excerpt($dangerous_text, 30);

echo $safe_excerpt;
?>

By using this `make_safe_excerpt()` function, even if the original text contains HTML tags, they will be safely displayed as mere strings, so you don't have to worry about them breaking the page layout or executing scripts.

4. Applied Example: Using it with a foreach loop

Now, let's combine this handy excerpt generation function with the `foreach` loop we learned about in the previous article. We will dynamically generate a list of titles and excerpts from an array of blog posts.

<?php
// Safe excerpt generation function (assumed to be defined from the previous example)
function make_safe_excerpt(string $text, int $length): string {
    $safe_text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    if (mb_strlen($safe_text) > $length) {
        return mb_substr($safe_text, 0, $length) . '...read more';
    }
    return $safe_text;
}

// Array of blog post data
$blog_posts = [
    [
        "title" => "Master the Basics of PHP",
        "content" => "This article explains the basic syntax and variables of PHP. It's designed for those new to programming, so please feel free to read on."
    ],
    [
        "title" => "The Secret to Database Connections",
        "content" => "Databases are essential for web development. By reading this article, you will understand how to connect to a MySQL database from PHP and retrieve/manipulate data in 5 minutes. Plenty of sample code is included."
    ]
];
?>

<div class="post-list">
    <?php foreach ($blog_posts as $post): ?>
        <article>
            <h3><?php echo htmlspecialchars($post['title']); ?></h3>
            <p><?php echo make_safe_excerpt($post['content'], 60); ?></p>
        </article>
    <?php endforeach; ?>
</div>

As you can see, a function, once created, can be called and used repeatedly in various parts of your site, such as inside loops. The high reusability of code and easier maintenance are the major attractions of functions.

5. Summary and Introduction to Related Code

In this article, we learned how to use PHP "functions" to cut text to a specified character count and generate a safe excerpt. The benefits of using functions are code organization and improved reusability. The `make_safe_excerpt` function we created today is sure to be a handy tool that will serve you well many times in your site creation projects.

PHP has many other useful functions for manipulating strings. For example, `mb_strpos()` to search for a specific string, `str_replace()` to perform replacements, and `strip_tags()` to completely remove HTML tags. By combining these functions, you can achieve even more advanced text processing. We encourage you to look them up and give them a try.