EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP strip_tags()

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP strip_tags()

PHP strip_tags()

Introduction to PHP strip_tags() Function

The strip_tags() function in PHP is an inbuilt one which strips/removes a string from HTML and PHP tags. This returns a string having a NULL value in bytes and HTML, PHP tags being removed/stripped from the given input string. This function is basically helpful when we display the input of the user to our site. For example, when we create our message forum on the site a user is able to post a title as follows: <h1>THIS SITE IS BAD!</h1>. If the website was to display all the titles of each post then this unwanted message would also get displayed on the site in heading format to all the visitors of the page. Hence by using this strip_tag() functions it would help in eradicating such issues.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

string strip_tags( $str, $allowed_tags )

Parameters Required: There are 2 parameters which the function accepts;

  • $str being the mandatory parameter and which is the main string which needs to be checked.
  • $allowed_tags is the non-mandatory parameter which describes the tags which are allowed and not to be stripped off. Hence these tags will be retained.

Return Value: This strip_tags function gives us the resultant string stripped off from the input string.

Exceptions:

  • This function does not provide validation of HTML.
  • Some of the things that are stripped by default are the HTML comments and PHP tags and these things cannot be changed as they are hard-coded.
  • The self-closing XHTML tags are ignored in versions after PHP 5.3.4 and hence only non-self-closing tags are allowed to be used in $allowed_tags.

Examples of PHP strip_tags() Function

Let us now take some examples to understand the working of PHP strip_tags function.

Example #1

Code:

<?php
// PHP programme to demostrate
// strip_tags function without $allowed_tags parameter
echo strip_tags("Hello <b>Sample Program!</b>");
?>

Output:

PHP strip_tags() Example 1

In the above example we are displaying a simple PHP code to illustrate that strip_tags function can be used without specifying the second parameter to specify which all characters are allowed. This means all the characters in the string are allowed and printed as is.

Example #2

Code:

<?php
$str = '<p>To test a paragraph.</p><!-- Starting comments --> <a href="#fragment">Another paragraph goes here</a>';
echo strip_tags($str);
echo "\n";
// Here we allow HTML tag <p>
echo strip_tags($str, '<p>');
// In the version till PHP 7.4.0 the above code can be written as:
// echo strip_tags($str, ['p', 'a']);
?>

Output:

PHP strip_tags() Example 2

In the above example we are first specifying the required HTML code and assigning the same to the input string $str. We then use strip tag function on that string by using only single parameter. Next we showcase the use of second parameter $allow_tags where we specify only the tag <p> meaning that only <p> tag should be allowed and rest all tags should be trimmed off. Hence in the output we can see that only <p> tag information is displayed and <a> tag information is not displayed. Also we can see that in the output the HTML comments are not printed and hence proves that HTML comments are trimmed by this function by default even if we do not specify in the second parameter list.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Warnings:

  • This function cannot be used to prevent certain attacks like XSS. There are other appropriate methods or functions like htmlspecialchars() which can be used for this purpose depending on what kind of output is required.
  • The function strip_tags() just trims off the HTML tags without really validating them. As a result, this may lead to broken tags or removal of more/less data than what is expected. Hence it should be taken care while specifying the second parameter of the function.
  • This function also does not support any modification on the parameters we specify in the $allowed_tags function also including the onmouseover and style attributes that some user may use to post a text to display to other users.
  • One more thing to note while using this function is that the tag names whose characters are greater than a specified length (1023 bytes) within the HTML will be treated as though invalid, irrespective of what we give in the $allowed_tags as parameters.

Example #3

Code:

<?php
$str = '<a title="" href="/index.html"><b>Some Text</b></a>
Just a sample text to showcase a paragraph coming in HTML body';
echo strip_tags_content($str);
function strip_tags_content($str) {
return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $str);
}
?>

Output:

PHP strip_tags() Example 3

In the above example we are using strip_tags function to remove the anchor tag along with its contents in its input string. PHP strip_tags will automatically remove both opening and closing HTML tags when they are being stripped.

Example #4

Code:

<?php
$str = '<?= \'<?= 1 ?>\' ?>2';
var_dump(strip_tags($str));
?>

Output:

PHP strip_tags() Example 4

This example shows how to strip contents from a nested PHP tag.

Example #5

Code:

<?php // Test.php
$str = '<br>Trial<br/>on<br />NewLine';
$d = strip_tags($str, '<br />');
var_dump($d); // Displays string(11) "TraialonNewLine" on output
?>

Output:

Displays string Example 5

In this example, we can see that we are allowing only contents inside <br/> string and this output here will change as we run in different versions of PHP.

Example #6

Code:

<?php
function strip_tags_d($a)
{
return is_array($a) ?
array_map('strip_tags_d', $a) :
strip_tags($a);
}
// Example
$arr1 = array('<b>Car</b>', '<i>Bat</i>', array('<b>Car</b>', '<i>Bat</i>'));
$arr1 = strip_tags_d($arr1);
// Output
print_r($arr1);
?>

Output:

Array Example 6

In the above example, we are displaying the use of recursive functions for strip_tags function. Hence in the output we can see that the array is printed in loops of 2.

Conclusion

As shown above, we saw how to strip some unwanted HTML and PHP tags from the code by using the strip_tags() function. This function can parse the input string and extract its structure. It usually trims or replaces the given HTML or PHP tags which we pass as a list of input arguments to be removed from the HTML document. This is also used in cases when we only need to trim PHP tags and not HTML and vice versa.

Recommended Article

This is a guide to the PHP strip_tags(). Here we discuss the Introduction to PHP strip_tags() Function and its examples along with Code Implementation. You can also go through our other suggested articles to learn more-

  1. PHP Frameworks
  2. PHP chop()
  3. PHP setlocale()
  4. PHP strtotime

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you