Php正则表达式重新排序多行

时间:2016-01-17 22:37:43

标签: php regex preg-replace preg-match fread

item.ini

这是我的ITEM文件,有很多项目。如您所见,fread期权订单彼此不同。我想fwrite该文件,并ITEM将其与ofc选项一起使用(我已尝试ID Color Defname Name Value )。订单必须是:

class B:

    def update_private_variable(self):
        self._A__private_variable = "Updated in B"

2 个答案:

答案 0 :(得分:0)

你可以这样工作:

// split whole file to get items in an array where each one looks like:
// 1]
// value...
// ...
$raw_items = explode('[ITEM ', file_get_contents('.../item.ini'));

foreach ($raw_items as $item) {
  // turn item lines into an array (see below about PHP_EOL)
  $raw_options = explode(PHP_EOL, trim($item));
  // get item #, which is always the 1st line, drop its ending "]"
  $item_no = substr(trim(array_shift($raw_options), 0, -1);

  foreach ($raw_options as &$option) {
    // turn option line into an array of words
    $option = explode(' ', trim($option));
    // get option name, which is always the 1st word
    $option_name = trim(array_shift($option);
    // populate clean items
    $items[$options[$option_name]] = implode(' ', $option);
  }
}
// then you can use $items[<item_no>][<option_name>]

根据您的具体情况,您可能会遇到有关行分隔符的问题 如果是这样,请通过替换:

来摆脱它
$raw_options = explode(PHP_EOL, trim($item));

由此:

str_replace(["\r\n", "\r"], "\n", $item);
$raw_options = explode("\n", trim($item));

答案 1 :(得分:0)

这可能是解决问题的一种奇怪方式,但我们可以使用正则表达式来解决它,例如标题读取。

如果我们有这样的字符串:

$string = '
[ITEM 1]  
defname itemname  
name just name  
id 953124  
value 52235  
color red  

[ITEM 2]  
value 522  
name hi  
id 5335  
color yellow  
defname thats 2  ';

我们可以使用preg_replace_callback,它将提取字符串的每一行并将其发送到我们选择进行处理的函数。在这里,我说让ITEM 1的每个部分作为自己的行,并将其发送到名为reorder_function的函数。

我已在表达式上方标记了每个部分,以便您可以看到它匹配的位置。然后,我只打印出新转换的字符串。

// MATCH THE PATTERNS, RUN THE MATCHES THROUGH THE 'reorder_function' FUNCTION AND SAVE THE RESULTS
//                                        1            2      3      4      5      6
$string = preg_replace_callback('~(\[ITEM \d+\]).*?\n(.*?)\n(.*?)\n(.*?)\n(.*?)\n(.*?)($|\n)~', 'reorder_function', $string);


// PRINT OUT THE RESULTS
print $string;

reorder_function函数看起来有些可怕,但它确实不是那么糟糕。大多数时候我都有很多评论占用空间。它基本上循环遍历包含您希望每个项目的顺序的数组,并且当它执行此操作时,它会检查每个匹配以查看它是否匹配&#34; ID&#34;,&#34;颜色&#34;等。当找到匹配时,它将其写入数组中的特定位置。填好所有位置后,数组将变为字符串,[ITEM 1]将使用函数的输出覆盖其内容。然后它移动到[ITEM 2]并重复该过程。

// FUNCTION THAT WILL TAKE THE MATCHES AND ORDER THEM APPROPRIATELY
function reorder_function($m) {

    // SET THE DEFAULTS
    $order_array = array( 1 => 'ID', 2 => 'Color', 3 => 'Defname', 4 => 'Name', 5 => 'Value' );
    $final_output_array = array($m[1]); // DEFINE AN ARRAY AND SET THE [ITEM X] TO THE FIRST VALUE


    // LOOP THROUGH THE ORDER ARRAY
    foreach ($order_array AS $key => $val) {

        // LOOP THROUGH THE MATCHES THAT HAVE BEEN FOUND
        foreach ($m AS $match_key => $match_val) {

            // IF THE MATCH FINDS "ID", THEN IT WILL ASSIGN THE VALUE AT POSITION "1"
            // FOR EACH ONE, IT WILL ASSIGN THE VALUE UNTIL WE ARE OUT OF VALUES TO TEST
            if (preg_match('~^\s*'.$val.'\s~i', $match_val)) {
                $final_output_array[$key] = $match_val; 
            }   

        }

    }

    // TURN THE ARRAY INTO A STRING AND SEND IT BACK TO THE preg_replace_callback FUNCTION
    return implode("\n", $final_output_array)."\n";

}

说完所有内容后,我们就明白了:

[ITEM 1]
id 953124  
color red  
defname itemname  
name just name  
value 52235  

[ITEM 2]
id 5335  
color yellow  
defname thats 2  
name hi  
value 522  

这是一个有效的演示:

http://ideone.com/JtYZlx