How to replace text between 2 tags with PHP

Free Scripts :: PHP :: String :: How to replace text between 2 tags with PHP

Author: Salman Javaid

Website: http://www.salman.be

  • 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='<p>Untitled Document</p>';
$startPoint='<p>';
$endPoint='</p>';
$newText='Welcome';

echo replaceTags($startPoint, $endPoint, $newText, $source);

Output

<p>Welcome</p>

Comments

No comments. Be the first one.

Leave a comment

Full Name*
Comments*
Security Code*

Our Partners

Getty Icons  Salman Creations
Free High Quality Images  Learn Free Languages 
Opal Hosting  R-Tech Solutions
  • Submit a Script

    Click here to submit your script.