Insert string between two markers
I have a requirement to insert a string between two markers.
Initially I get a sting (from a file stored on the server) between #DATA# and #END# using:
function getStringBetweenStrings($string,$start,$end){
$startsAt=strpos($string,$start)+strlen($start);
$endsAt=strpos($string,$end, $startsAt);
return substr($string,$startsAt,$endsAt-$startsAt);
}
I do some processing and based on the details of the string, query for some records. If there are records I need to be able to append them at the end of the string and then re-insert the string between #DATA# and #END# within the file on the server.
How can I best achieve this?
Is it possible to insert a record at a time in the file before #END# or is it best to manipulate the string on the server and just re-insert over the existing string in the file on the server?
Example of Data:
AGENT_REF^ADDRESS_1^ADDRESS_2^ADDRESS_3^ADDRESS_4^TOWN^POSTCODE1^POSTCODE2^SUMMARY^DESCRIPTION^BRANCH_ID^STATUS_ID^BEDROOMS^PRICE^PROP_SUB_ID^CREATE_DATE^UPDATE_DATE^DISPLAY_ADDRESS^PUBLISHED_FLAG^LET_RENT_FREQUENCY^TRANS_TYPE_ID^NEW_HOME_FLAG^MEDIA_IMAGE_00^MEDIA_IMAGE_TEXT_00^MEDIA_IMAGE_01^MEDIA_IMAGE_TEXT_01^~
#DATA#
//Property records would appear here and match the string above, each field separated with ^ and terminating with ~
//Once the end of data has been reached, it will be fully terminated with:
#END#
When I check for new properties, I do the f开发者_如何学Goollowing:
- Get all existing properties between #DATA# and #END#
- Get the IDs of the properties and query for new properties which don't match these IDs
I then need to re-insert the new properties before #END# but after the last property in the file.
The structure of the file is a Rightmove BLM file.
Just do an str_replace() of the old data with the new:
$str = str_replace('#DATA#'.$oldstr.'#END#', '#DATA#'.$newstr.'#END#', $str);
I would extract the data in 3 steps:
1) Extract the data from the file:
<?php
preg_match("/#DATA#(.+)#END#/s", $string, $data);
?>
2) Extract each row of data:
<?php
preg_match_all("/((?:.+\^){2,})~/", $data[1], $rows, PREG_PATTERN_ORDER);
// The rows with data will be stored in $rows[1]
?>
3) Manipulate the data in each row or add new rows:
<?php
//Add
// Add new row to the end of the array
$data[1][] = implode('^', $newRowArray);
//Use
// Creates an array with all the data from the row '0'
$rowData = preg_split("/\^/", $data[1][0], -1, PREG_SPLIT_NO_EMPTY);
//Save the changes
//$newData should be all the rows together (with the '~' at the end of each row)
//$string is the original string with all the information
$file = preg_replace("/(#DATA#\r?\n).+(\r?\n#END#)/s", "\1".$newData."\2", $string);
I hope this can help you in your problem.
精彩评论