IT & Programming

Replace text between 2 tags with PHP

  • How to replace text between 2 tags with PHP.
  • Replace string between two points with PHP.
  • Replacing string among two strings using preg_replace.

This function accepts 4 parameters. start point, end point, new text and the source. It replace the string between 2 points or tags.

Function

function replaceTags($startPoint, $endPoint, $newText, $source) {

    return preg_replace('#('.preg_quote($startPoint).')(.*)('.preg_quote($endPoint).')#si', '$1'.$newText.'$3', $source);
}

Calling The Function

$source='Untitled Document';
startPoint='< p>';
$endPoint='< /p>';
$newText='Welcome';

Output

< p>Welcome< /p>

Comments

  1. Bas Van De Steeg June 06, 2012

    Omg thanks, i was searching for this

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *