PHP Strip_Tags Vs. Preg_Replace

PHP Strip_Tags Vs. Preg_Replace thumbnail
PHP is optimized for string manipulation.

PHP is a server-side language for the development of rich, interactive Web applications. While developing your unique Web applications, it may be necessary to interact with HTML or other source code, in order to process or display it along with your PHP code. Either the "strip_tags()" or "preg_replace()" functions may be used for this purpose.

  1. Strip_Tags

    • The "strip_tags()" function removes specified HTML and PHP code tags from a string. However, "strip_tags()" does not validate the HTML code in a string or check for malformed tags. If the string contains malformed tags, it may result in unwanted behavior, such as removing unintended text. HTML and PHP comments are always stripped from strings using "strip_tags()."

    Usage

    • The "strip_tags()" function has two input arguments: the input string and an optional argument specifying HTML or PHP tags which should be allowed in the string. However, if the closing angle bracket was left off the opening "<div>" tag in "$my_string," "strip_tags()" would remove the entire string.

      <?php
      $my_string = "<div><table><tr><td><i>This</i> is <b>my</b><br><u>string</u>.</td></tr></table></div>";
      //Allow tags for text markup
      $allowable_tags = "<b><i><u><br>";

      $stripped_string = strip_tags($my_string);
      $stripped_string_w_markup = strip_tags($my_string,$allowable_tags);

      ?>

    Preg_Replace

    • The "preg_replace()" function replaces substrings in a PHP string using regular expression to define search patterns. Although "strip_tags()" is simpler to use, using "preg_replace()" may be necessary if your strings may contained malformed HTML or PHP tags. To remove substrings, such as HTML or PHP tags, using "preg_replace()" use an empty string as the specified replacement string.

    Usage

    • The usage of "preg_replace()" is more complex than that of "strip_tags()." The "preg_replace()" function requires three required argument and two optional arguments: the regular expression pattern, the replacement string, and the subject string as well as optional replacement limits or a specified replacement count.

      <?php
      $my_string = "<div><table><tr><td><i>This</i> is <b>my</b><br><u>string</u>.</td></tr></table></div>";
      //Replace text between angle brackets in a case-insensitive manner
      $pattern = "/<[^>]+>/i";
      $replacement = "";

      $stripped_string = preg_replace($pattern,$replacement,$my_string);
      ?>

Related Searches:

References

  • Photo Credit John Foxx/Stockbyte/Getty Images

Comments

Related Ads

Featured