PHP: How to Replace a String Between Tags

Nearly all Web data exchange formats, from HTML to XML, use tags as a way to separate data into usable bits. However, working directly with the data using the most basic string functions in PHP can be a challenge. It is for this reason that PHP supports regular expressions (regex), an industry standard syntax that can be used to perform complex find and replace operations on strings. Using regex, you define a pattern that PHP searches for and how it ought to be replaced.

Instructions

    • 1

      Open a text editor or your favorite PHP Integrated Development Environment (IDE).

    • 2

      Type or paste the following into your editor:

      #!/usr/bin/php

      <?php

      $tags = '<xml>Some data between two xml tags</xml>';

      $pattern = '/<(\w+)>.+<\/\w+>/s';

      $replacement = '<${1}>This is a replacement</${1}>';

      echo preg_replace($pattern, $replacement, $tags);

      ?>

      The key lines are the ones that begin with "$pattern" and "$replacement." The pattern looks for a word between two arrow brackets to be the tag, some information between the tags and another closing tag between arrow brackets with a backslash.

      The "replacement" pattern rebuilds the found string from scratch using the originally detected tag and the new text.

    • 3

      Save your work and double-click the file to run it through PHP. The output will be:

      <xml>This is a replacement</xml>

Tips & Warnings

  • Regex syntax is a complicated subject; see Resources to learn more about it.

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured