← Back to Chapters

PHP strip_tags() & wordwrap()

? PHP strip_tags() & wordwrap()

? Quick Overview

The strip_tags() and wordwrap() functions in PHP are used to manipulate strings by removing HTML tags and wrapping long lines of text, respectively.

? Key Concepts

  • strip_tags() – Removes HTML and PHP tags from a string.
  • wordwrap() – Wraps a string to a given number of characters, inserting line breaks.

? Syntax & Theory

  • strip_tags(string, allowed_tags) cleans unwanted markup.
  • wordwrap(string, width, break, cut) improves text readability.

? Code Example: strip_tags()

? View Code Example
// Remove all HTML tags and keep only plain text
<?php
$string = "<h1>Welcome to PHP</h1><p>This is a paragraph.</p>";
$clean_text = strip_tags($string);
echo $clean_text;
?>

? Output / Explanation

The HTML tags are stripped, leaving readable plain text without markup.

? Code Example: wordwrap()

? View Code Example
// Wrap long text at 40 characters with line breaks
<?php
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
$wrapped_text = wordwrap($text, 40, "<br>\n");
echo $wrapped_text;
?>

? Output / Explanation

The text is broken into multiple lines at 40 characters, improving readability in HTML output.

? Interactive Example

Click the button to see how text wrapping improves readability by constraining the container width.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

? Use Cases

  • Sanitizing user input before display.
  • Formatting email bodies or logs.
  • Preparing text for fixed-width layouts.

✅ Tips & Best Practices

  • Use strip_tags() to prevent unwanted HTML rendering.
  • Preserve safe tags using the optional parameter.
  • Choose a reasonable wrap width for better readability.

? Try It Yourself

  • Clean form input using strip_tags().
  • Wrap long text inside a paragraph using wordwrap().
  • Experiment with allowed HTML tags.