www.softwareriviera.com
Software Code
    New Code     Most Interesting     Don't Miss     Our picks  
PHP - section

View Article
PHP Replace string between tags
PHP Replace string between tags. This function replaces a string between two tags with a processed string (in this case the processing of the string between the tags is done by the unhtmlentities function but of course, this can be replaced with any other function you choose)
This function replaces a string between two tags with a processed string and:
- takes a string as a paramater
- applies the unhtmlentities PHP function to the string contained between the two tags: STARTTAGCODE1 start and ENDTAGCODE1
- must have the two tags STARTTAGCODE1 and ENDTAGCODE1 in a strict order: first STARTTAGCODE1 comes then some string content follows and then ENDTAGCODE1


function replaceThisString($theString){
$result = $theString;
$codeStart = "STARTTAGCODE1";//START TAG CODE 1
$codeEnd = "ENDTAGCODE1";//END TAG CODE 1
$lookForStart = strpos($result, $codeStart);
$lookForEnd = strpos($result, $codeEnd);
$start = $codeStart;
$end = $codeEnd;
while($lookForStart !== false && $lookForEnd !== false){
$original = $result;
$result = "";
$lastPos = 0;
$initialPoz = strpos($original, $start);
$result = substr($original, $lastPos, $initialPoz);
$lastPos += $initialPoz + strlen($start);
$endPoz = strpos($original, $end);
$diffPoz = $endPoz - $initialPoz - strlen($end);
$innerSubtring = substr($original, $lastPos, $diffPoz);
$innerSubtring = unhtmlentities($innerSubtring);
$result = $result.$innerSubtring;
$result = $result.substr($original, $lastPos + strlen($end) + $diffPoz);
$lookForStart = strpos($result, $start);
$lookForEnd = strpos($result, $start);
}//END WHILE
$resReplace = $result;
return $resReplace;
}//END FUNCTION
NOTE: INSTEAD OF THE UNHTMLENTITIES FUNCTION ABOVE YOU CAN ADD ANY OTHER FUNCTION YOU WANT TO MODIFY THE CONTENT BETWEEN THE TWO TAGS
Example on how to use the PHP replaceThisString function:

//Choose a string containing the STARTTAGCODE1 and ETAGCODE1 tags (one after the other having some string in between)
$myOriginalString = "Hello world!STARTTAGCODE1What a cool function this is!ETAGCODE1";

//Now call the function with the string above as the paramater
$myOriginalString = replaceThisString( $myOriginalString );

// And of course, the outpus is: "Hello World!What a cool functions this is!";
Date: 2007-5-20    Written by: Admin A
     See all articles in this section
Copyright © 2007-2009 SoftwareRiviera.com. All rights reserved.  | Terms of use | Disclaimer | Privacy Policy |