将特定格式的文本转换为真正的 PHP 代码分配


Convert text in specific format into real PHP code assignments

我在将特定格式的文本放入实际工作的PHP代码中遇到了一些问题。

我的文本文件:

@T1:The German sociologist Max Weber once proposed
@S:Jos Bleau
@C:jos.bleau@domain.com
@L:"He used to be so conservative," she says, throwing up her hands in mock exasperation. "We used to have the worst arguments right here at this table. I was part of the first group of public city school teachers that struck to form a union, and Richard was very angry with me. He saw unions as corrupt. He was also very opposed to social security. He thought people could make much more money investing it on their own. Who knew that within 10 years he would become so idealistic
@R:At first, <@Ri>Stallman viewed these notices<@$p> with alarm. Rare was the software program that didn't borrow source code from past programs, and yet, with a single stroke of the president's pen, Congress had given programmers and companies the power to assert individual authorship over communally built programs. It also injected a dose of formality into what had otherwise been an informal system.
The AI Lab of the 1970s was by all accounts a special place. Cutting-edge projects and top-flight researchers gave it an esteemed position in the world of computer science. The internal hacker culture and its anarchic policies lent a rebellious mystique as well. Only later, when many of the lab's scientists and software superstars had departed, would hackers fully realize the unique and ephemeral world they had once inhabited.
As a single parent for nearly a decade-she and Richard's father, Daniel Stallman, were married in 1948, divorced in 1958, and split custody of their son afterwards-Lippman can attest to her son's aversion to authority. She can also attest to her son's lust for knowledge. It was during the times when the two forces intertwined, Lippman says, that she and her son experienced their biggest battles.
@ST:Fusions
@R:Such mythological descriptions, while extreme, underline an important fact. The ninth floor of 545 Tech Square was more than a workplace for many. For hackers such as Stallman, it was home.
The belief in individual freedom over arbitrary authority extended to school as well. Two years ahead of his classmates by age 11, Stallman endured all the usual frustrations of a gifted public-school student. It wasn't long after the puzzle incident that his mother attended the first in what would become a long string of parent-teacher conferences.
@ST:Fusions
@R:The belief in individual freedom over arbitrary authority extended to school as well. Two years ahead of his classmates by age 11, Stallman endured all the usual frustrations of a gifted public-school student. It wasn't long after the puzzle incident that his mother attended the first in what would become a long string of parent-teacher conferences.
@BV:Thirty years later, Breidbart remembers
@CP:(Picture: Credit – Jos Bleau) or @CP:(Picture: Thanks)

我需要的预期输出(半伪代码;未转义的引号(:

<?php
$title1 = 'The German sociologist Max Weber once proposed';
$signature = 'Jos Bleau';
$email = 'jos.bleau@domain.com';
$lead = '"He used to be so conservative," she says, throwing up her hands in mock exasperation. "We used to have the worst arguments right here at this table. I was part of the first group of public city school teachers that struck to form a union, and Richard was very angry with me. He saw unions as corrupt. He was also very opposed to social security. He thought people could make much more money investing it on their own. Who knew that within 10 years he would become so idealistic';   
$text[] = 'At first, <@Ri>Stallman viewed these notices<@$p> with alarm. Rare was the software program that didn't borrow source code from past programs, and yet, with a single stroke of the president's pen, Congress had given programmers and companies the power to assert individual authorship over communally built programs. It also injected a dose of formality into what had otherwise been an informal system.
The AI Lab of the 1970s was by all accounts a special place. Cutting-edge projects and top-flight researchers gave it an esteemed position in the world of computer science. The internal hacker culture and its anarchic policies lent a rebellious mystique as well. Only later, when many of the lab's scientists and software superstars had departed, would hackers fully realize the unique and ephemeral world they had once inhabited.
As a single parent for nearly a decade-she and Richard's father, Daniel Stallman, were married in 1948, divorced in 1958, and split custody of their son afterwards-Lippman can attest to her son's aversion to authority. She can also attest to her son's lust for knowledge. It was during the times when the two forces intertwined, Lippman says, that she and her son experienced their biggest battles.'; 
$subtitle[] = 'Fusions';
//etc...
?>

注意:

  • $title1@T1这样的名称彼此完全无关,$title1只是用作示例。它也可能是$xy或其他东西

  • 如果@XY在文件中多次出现,则应将值添加为数组元素,否则作为简单赋值添加

我不知道preg_split()方向是否正确,我可以用它来做吗?还是我必须使用其他功能来完成此操作?

解释

首先,我们将文本文件中的数据获取到带有 file_get_contents() 的变量中,并初始化我们的 $output 数组,其中每个元素都是输出中的一行,并带有 php 标签<?php .

您还可以使用shortcut => variable name元素修改$lookup,您可以在其中定义将哪些@XY:替换为哪个变量名称。如果未定义,快捷方式将用作变量名。

现在我们已经准备了一些东西,我们将每个@XY:与相应的数据进行匹配 preg_match_all() .

正则表达式

/@('w+):(.*?)(?=@'w+:)/s
  • 'w+匹配所有单词字符'[a-zA-Z0-9_'],这是@XY:的XY部分,我们将其与捕获组一起保存
    • + 是一个量词,表示'w应该匹配 1 次或更多次
  • (.*?)根据需要匹配所有内容
    • 随着标志s*也匹配新行
  • (?=@'w+:)确保(.*?)匹配所有内容,直到下一个@XY:而不是更多。其中?=是一个积极的展望,正如它所说,如果括号(@'w+(中的正则表达式可以匹配,它就会向前看

我们还预先保存数据中出现的每个快捷方式的数量,并带有array_count_values()

现在我们已经匹配了我们想要的所有数据,我们可以遍历所有快捷方式,这些快捷方式保存在 $m[1] .在foreach循环中,我们只需检查您是否定义了查找变量名称,或者我们是否使用快捷方式作为变量名称。

然后我们只需将每个赋值作为新元素添加到输出数组中。您必须注意三件事:

  • 使用复杂(卷曲(语法,以免遇到无效变量名称的问题,请参阅:如何访问名称无效的属性?

  • 根据快捷方式在数据中出现的次数,我们决定是否应将其添加为数组元素或正常赋值。如果快捷方式在数据中多次出现,它将把值添加为数组元素,否则作为简单的字符串赋值

  • 我们使用trim()来删除空格、新行...从字符串的开头和结尾。我们使用addslashes(),所以我们不会遇到引号的问题

做。现在我们已经完成了。根据您希望如何输出结果,您可以将其保存到带有file_put_contents()的文件中,或者只是打印出数组。

法典

<?php
    $text = file_get_contents("test.txt");
    $output = ["<?php"];
    $lookup = [];  //Example: ["ST" => "subtitle"]
    preg_match_all("/@('w+):(.*?)(?=@'w+:)/s", $text, $m);
    $variableShortcutCount = array_count_values($m[1]);
    foreach($m[1] as $key => $variableShortcut){
        if(isset($lookup[$variableShortcut])){
            $output[] = '${"' . $lookup[$variableShortcut] . ($variableShortcutCount[$variableShortcut] > 1 ? '"}[]' : '"}') . " = '". addslashes(trim($m[2][$key])) . "';" ;
        } else {
            $output[] = '${"' . $variableShortcut . ($variableShortcutCount[$variableShortcut] > 1 ? '"}[]' : '"}') . " = '". addslashes(trim($m[2][$key])) . "';" ;
        }
    }
    //Output to file
    //file_put_contents("output.txt", implode(PHP_EOL, $output));
    //Output to browser
    echo "<pre><code>";
    highlight_string(implode(PHP_EOL, $output));
?>

输出:

<?php
${"T1"} = 'The German sociologist Max Weber once proposed';
${"S"} = 'Jos Bleau';
${"C"} = 'jos.bleau@domain.com';
${"L"} = ''"He used to be so conservative,'" she says, throwing up her hands in mock exasperation. '"We used to have the worst arguments right here at this table. I was part of the first group of public city school teachers that struck to form a union, and Richard was very angry with me. He saw unions as corrupt. He was also very opposed to social security. He thought people could make much more money investing it on their own. Who knew that within 10 years he would become so idealistic';
${"R"}[] = 'At first, <@Ri>Stallman viewed these notices<@$p> with alarm. Rare was the software program that didn''t borrow source code from past programs, and yet, with a single stroke of the president''s pen, Congress had given programmers and companies the power to assert individual authorship over communally built programs. It also injected a dose of formality into what had otherwise been an informal system.
The AI Lab of the 1970s was by all accounts a special place. Cutting-edge projects and top-flight researchers gave it an esteemed position in the world of computer science. The internal hacker culture and its anarchic policies lent a rebellious mystique as well. Only later, when many of the lab''s scientists and software superstars had departed, would hackers fully realize the unique and ephemeral world they had once inhabited.
As a single parent for nearly a decade-she and Richard''s father, Daniel Stallman, were married in 1948, divorced in 1958, and split custody of their son afterwards-Lippman can attest to her son''s aversion to authority. She can also attest to her son''s lust for knowledge. It was during the times when the two forces intertwined, Lippman says, that she and her son experienced their biggest battles.';
${"subtitle"}[] = 'Fusions';
${"R"}[] = 'Such mythological descriptions, while extreme, underline an important fact. The ninth floor of 545 Tech Square was more than a workplace for many. For hackers such as Stallman, it was home.
The belief in individual freedom over arbitrary authority extended to school as well. Two years ahead of his classmates by age 11, Stallman endured all the usual frustrations of a gifted public-school student. It wasn''t long after the puzzle incident that his mother attended the first in what would become a long string of parent-teacher conferences.';
${"subtitle"}[] = 'Fusions';
${"R"}[] = 'The belief in individual freedom over arbitrary authority extended to school as well. Two years ahead of his classmates by age 11, Stallman endured all the usual frustrations of a gifted public-school student. It wasn''t long after the puzzle incident that his mother attended the first in what would become a long string of parent-teacher conferences.';
${"BV"} = 'Thirty years later, Breidbart remembers';
${"CP"} = '(Picture: Credit – Jos Bleau) or';