PHP Strip Tags With Best Example

Definition and Usage of PHP strip_tags

The strip_tags() function is a built-in PHP function used to strip HTML and PHP tags from a string.

This function returns a string that has been stripped of any NULL bytes, HTML, and PHP tags.

Syntax:

strip_tags( string, allowed_tags )

Parameters:

The following are the parameters of strip_tags in PHP:

  • string – It’s a required parameter that tells the program what string to check.
  • allowed_tags – It’s an optional parameter that lists the tags that are allowed. These tags will not be removed.

Return Values:

It returns the stripped string.

Exceptions

The following are the exceptions of strip_tags in PHP:

  • This function gets rid of HTML tags and comments. It can’t be used this way in allowed_tags, because it’s already set up that way.
  • PHP 5.3.4 and later versions did not care about XHTML tags that closed themselves.
  • strip_tags() does not validate the HTML.

Changelog

The following changelogs are based on PHP official documentation:

VersionDescription
8.0.0allowed_tags is nullable now.
7.4.0The allowed_tags now alternatively accepts an array.

Strip_tags Examples

The following examples show how to use PHP strip_tags() function:

Example 1:

<?php
    // declaration of str variable
    $str = "Where source code is not a <b>PROBLEM!</b>";
    
    // original string
    echo ("Original String: ".$str);
    echo("<br>");
    
    // strip_tags function without allowed_tags
    echo ("Strip String: ".strip_tags($str));
?>

Output:

Original String: Where source code is not a PROBLEM!
Strip String: Where source code is not a PROBLEM!

In the above example, the strip_tags function does not care about the <b> tag. Because of this, the result of the example code is not in HTML format.

Example 2:

We will use the same example above, but this time we will allow the <b> tag for our string.

<?php
    // declaration of str variable
    $str = "Where source code is not a <b>PROBLEM!</b>";
    
    // original string
    echo ("Original String: ".$str);
    echo("<br>");
    
    // strip_tags function without allowed_tags
    echo ("Strip String: ".strip_tags($str, "<b>"));
?>

Output:

Original String: Where source code is not a PROBLEM!
Strip String: Where source code is not a PROBLEM!

In this example, we made the string work with the <b> tag. This makes the word “PROBLEM!” stand out by making it bold.

Example 3:

In this example, we are going to use multiple HTML tags inside our strip_tags.

<?php
    // declaration of str variable
    $str = "<h2>Where <i>source code</i> is not a <b>PROBLEM!</b></h2>";
    
    // original string
    echo ("Original String: ".$str);
    echo("<br>");
    
    // strip_tags function without allowed_tags
    echo ("Strip String: ".strip_tags($str, ["<i>", "<h2>"]));
?>

Output:

Original String:
Where source code is not a PROBLEM!

Strip String:
Where source code is not a PROBLEM!

By using multiple allowed_tags, we have to enclose the allowed_tags with square brackets [].

Without these, it will prompt an error.

We can also put the multiple allowed_tags in quotation a mark.

See the example below:

<?php
    // declaration of str variable
    $str = "<h2>Where <i>source code</i> is not a <b>PROBLEM!</b></h2>";
    
    // original string
    echo ("Original String: ".$str);
    echo("<br>");
    
    // strip_tags function without allowed_tags
    echo ("Strip String: ".strip_tags($str, "<i><h2>"));
?>

Output:

Original String:
Where source code is not a PROBLEM!

Strip String:
Where source code is not a PROBLEM!

Example 4:

In the following example, we are going to use an <br> tag, and we will see what happens if we allow it.

<?php
    // declaration of str variable
    $str = "<br>Where<br/>Source<br />Code<br>IsNotAProblem";

    // original string
    $original_string = strip_tags($str);
    echo("Original: ".$original_string);
    
    echo ("<br>");
    
    // strip_tags function with allowed_tags
    $stripped_string = strip_tags($str, '<br>');
    echo("Stripped: ".$stripped_string);
?>

Output:

Original: WhereSourceCodeIsNotAProblem
Stripped:
Where
Source
Code
IsNotAProblem

In this example, we can see that we are only allowing information within the <br/> string, and that the output will vary depending on the version of PHP that is being used.

Example 5:

In the following example, we are going to use an array.

<?php
function strip_tags_func($str)
{
    return is_array($str) ?
    array_map('strip_tags_func', $str) :
    strip_tags($str);
}
// Example
$arr1 = array('<b>Prince</b>', '<i>Grace</i>', array('<b>Nym</b>', '<i>Nymheria</i>'));

$original = strip_tags_func($arr1);
// Output
echo("<pre>Original:<br>");
print_r($original);
?>

Output:

Original:
Array
(
    [0] => Prince
    [1] => Grace
    [2] => Array
        (
            [0] => Nym
            [1] => Nymheria
        )

)

The above examples show the use of recursive functions within the strip_tags function.

Therefore, the results show that the array is written in 2-loop iterations.

Frequently Ask Question

What is strip_tags function in PHP?

PHP’s strip_tags() method is used to remove HTML, XML, and PHP tags from a string. It is a function that is safe for binary data.

What is strip HTML?

The HTML tag remover strips HTML formatting from the text and turns HTML code into text so it can be saved and shared as text.

HTML stripping is the process of removing of any HTML tags on a web page that isn’t needed.

What is the use of strips function in PHP?

The strip_tags() function extracts a string from a text by removing HTML, XML, and PHP tags.

There is one required parameter and one optional parameter for this function.

The optional argument allows specific tags to be accepted.

Summary

In summary, we have discussed what the stip_tags function is in PHP and how to implement it into practical code.

Using the strip_tags() function, we showed how to remove some unneeded HTML and PHP tags from the code.

This function can extract the structure from the input string by parsing it.

Typically, it trims or replaces the HTML or PHP tags that we pass as an array of input arguments to be eliminated from the HTML content.

This is also used when only PHP tags and not HTML tags need to be trimmed, and vice versa.

Lastly, if you want to learn more about PHP strip_tags, please leave a comment below. We’ll be happy to hear it!

Common use cases for PHP Strip Tags With Best Example

  • Web application development. Full-stack PHP apps using vanilla PHP or Laravel/Symfony frameworks.
  • WordPress plugin/theme development. Custom functionality for the world’s most popular CMS.
  • API development. REST or GraphQL endpoints serving mobile apps and SPAs.
  • CLI tools. Command-line scripts for cron jobs, data migration, or automation.
  • Legacy code maintenance. PHP powers a large share of the web; understanding it is a durable skill.

Working code example

<?php
declare(strict_types=1);

class UserService {
    public function getGreeting(string $name): string {
        if ($name === "") {
            throw new InvalidArgumentException("Name is required");
        }
        return "Welcome, " . htmlspecialchars($name);
    }
}

$service = new UserService();
echo $service->getGreeting("Alice");
?>

Best practices

  • Enable strict types. declare(strict_types=1) at the top of every file catches type coercion bugs.
  • Use Composer. Modern PHP uses Composer for dependency management, autoloading, and PSR-4 class naming.
  • Follow PSR standards. PSR-12 for coding style, PSR-4 for autoloading, PSR-3 for logging.
  • Write unit tests with PHPUnit. Aim for 70%+ code coverage on business-critical modules.
  • Use static analysis. PHPStan or Psalm catch many bugs before code runs.

Common pitfalls

  • Global state. Overusing global variables makes testing hard. Prefer dependency injection.
  • SQL concatenation. Always use prepared statements. Never concatenate user input into SQL strings.
  • Missing type declarations. Old PHP allowed loose types. Modern PHP encourages strict typing everywhere.
  • Ignoring errors. Set error_reporting(E_ALL) in development. Handle errors explicitly in production.

Frequently Asked Questions

What PHP version does this tutorial target?
This tutorial is written for PHP 8.0 or higher. Modern features (arrow functions, named arguments, match expressions, enums, nullsafe operator) work best in PHP 8.1+. For legacy PHP 7.x, most examples still run but with fallback syntax.
Do I need XAMPP to run PHP code examples?
For beginners, XAMPP (Apache + PHP + MySQL) is the easiest setup on Windows. On Mac, use MAMP or Homebrew php. On Linux, install php-cli via apt or yum. For quick one-off tests, use an online PHP sandbox like PHP Sandbox or 3v4l.org.
How do I test the code snippets in this tutorial?
Save each example as a .php file inside XAMPP htdocs folder, start Apache in XAMPP Control Panel, then open http://localhost/yourfile.php in a browser. For pure PHP CLI code, run php yourfile.php from the terminal.
Can I use this in a Laravel project?
Yes. Most native PHP functions covered in these tutorials work identically inside Laravel. Some Laravel helpers (str_helpers, arr_helpers) provide framework-specific wrappers around the same functions.
Where can I get more PHP practice projects?
Browse itsourcecode.com PHP Projects for 300+ free capstone-ready systems (POS, inventory, hospital management, e-commerce). Each includes source code, database SQL, and installation guide for BSIT capstone students.

Leave a Comment