jelix/properties-file

类用于读取和写入属性文件。格式类似于Java属性文件。

v1.2.3 2022-06-29 13:09 UTC

This package is auto-updated.

Last update: 2024-08-29 05:06:17 UTC


README

一些用于读取和写入属性文件的类。

属性文件类似于Java属性文件。实现的格式用于存储使用Jelix(一个PHP框架)创建的应用程序的区域。

安装

该库与PHP 5.6到PHP 8.1兼容。

您可以使用Composer安装它。在您的项目中

composer require "jelix/properties-file"

使用方法

您有两个类:Properties,它是一个键/值对的容器,一个Reader用于解析属性文件,一个Writer用于将属性写入文件。

use \Jelix\PropertiesFile\Properties;
use \Jelix\PropertiesFile\Parser;
use \Jelix\PropertiesFile\Writer;

$properties = new Properties();

$reader = new Parser();
$reader->parseFromFile('file.properties', $properties);

$value = $properties->get('a_key');
$value = $properties['a_key'];

$properties->set('a_key', 'new_value');
$properties['a_key'] = 'new_value';

$writer = new Writer();
$writer->writeToFile($properties, 'file.properties');

// with a limit of line length (default is 120)
$writer->writeToFile($properties, 'file.properties', 
                    array("lineLength"=>80));

Writer的选项

  • lineLength:行的最大长度。如果字符串长度更高,它将被分割。(默认:120)
  • cutOnlyAtSpace:在有空格的行中进行分割,而不是在单词的中间(默认:true)
  • spaceAroundEqual:在等号周围添加或删除空格(布尔值,默认:true)
  • headerComment:在头部添加注释(字符串,默认:空字符串)
  • removeTrailingSpace:从值中删除尾随空格(布尔值,默认:false)
  • encoding:写入值的编码。(字符串,默认:"UTF-8")

历史记录

解析器基于来自Jelix框架的jBundle类,直到Jelix 1.6,并于2018年作为Jelix\PropertiesFile\Parser发布到单独的存储库。

格式

文件内容结构相当简单。它基本上是一个key=string结构,进行了一些改进。

您不能使用双引号和单引号来限定字符串,换行符可以做到这一点。

键可以包含字符az(小写/大写)、数字以及字符_-.

以下是一个文件示例

title.offlineElements = elements to check
title.onlineElements = online elements
buttons.save = Save
buttons.ok=Ok

多行

如果文本很长,并且您想将其写入多行,您可以在每行的末尾(除了文本的最后一行)键入反斜杠\,以告诉解析器继续读取翻译后的字符串。

intro=this is a very very\
long text in\
several lines
message=this is a regular line

但是,它不会在显示的字符串中插入换行符。如果您想插入真正的换行符,请使用\n\r(Windows上的\r\n,Linux上的\n,Mac上的\r)。

intro=this is a very very \
long text in\nseveral lines, but in\n one line\nin the source

注释

您还可以添加一些注释。它们必须以#开头。当解析器看到#时,该行其余部分将被忽略。注释可以位于行的开头、中间或末尾。如果您想在值中使用#,必须用反斜杠转义:\#

空白符

在值前后添加的空白符将被忽略。如果您想将值设置为空格,必须使用\s

nospace= #this is using a regular space
space= \s#this is using a \s space

space的值将是' ',而nospace的值是空字符串。

您还可以使用\S插入一个“不可分割”的空格。