【问题标题】:Insert string between two markers在两个标记之间插入字符串
【发布时间】:2010-04-08 07:59:37
【问题描述】:

我需要在两个标记之间插入一个字符串。

最初,我在 #DATA# 和 #END# 之间得到一个刺痛(来自存储在服务器上的文件):

function getStringBetweenStrings($string,$start,$end){ 
    $startsAt=strpos($string,$start)+strlen($start);
 $endsAt=strpos($string,$end, $startsAt);
 return substr($string,$startsAt,$endsAt-$startsAt);
} 

我做了一些处理,根据字符串的详细信息,查询一些记录。如果有记录,我需要能够将它们附加到字符串的末尾,然后在服务器上的文件中重新插入 #DATA# 和 #END# 之间的字符串。

我怎样才能最好地做到这一点?

是否可以在 #END# 之前的文件中一次插入一条记录,还是最好在服务器上操作字符串并重新插入服务器上文件中的现有字符串?

数据示例:

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#

当我检查新属性时,我会执行以下操作:

  1. 获取#DATA# 和#END# 之间的所有现有属性
  2. 获取属性的 ID 并查询与这些 ID 不匹配的新属性

然后我需要在 #END# 之前但在文件中最后一个属性之后重新插入新属性。

文件结构是 Rightmove BLM 文件。

【问题讨论】:

  • 请举例说明您需要处理的数据
  • 这个问题有点不清楚。请提供一些示例数据和结果示例。
  • 如何获取属性的 ID? AGENT_REF 是 ID 吗?

标签: php string insert strpos


【解决方案1】:

只需用新数据对旧数据执行 str_replace():

$str = str_replace('#DATA#'.$oldstr.'#END#', '#DATA#'.$newstr.'#END#', $str);

【讨论】:

    【解决方案2】:

    我将分 3 步提取数据:

    1) 从文件中提取数据:

    <?php
    preg_match("/#DATA#(.+)#END#/s", $string, $data); 
    ?>
    

    2) 提取每一行数据:

    <?php
    preg_match_all("/((?:.+\^){2,})~/", $data[1], $rows, PREG_PATTERN_ORDER);
    // The rows with data will be stored in $rows[1]
    ?>
    

    3) 操作每一行中的数据或添加新行:

    <?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);
    

    我希望这可以帮助您解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      相关资源
      最近更新 更多