我有一个嵌套数组,模拟表格布局(列和行):
{
"1": [
{
"row": "My name is Trevor\n"
},
{
"row": "Can you see me?\n"
},
{
"row": "\f"
}
],
"2": [
{
"row": Hey there! Some other text.\n"
},
{
"row": "What is up?\n"
},
{
"row": "\f"
}
],
"3": [
{
"row": "Some text on the third column. First row."
},
{
"row": "\f"
}
]
}
所以,“1”,“2”,“3”是列,然后在每个列下面,可以有任意数量的行。
现在我正在尝试让我的用户对以下内容执行各种解析规则:
1. 所有列和所有行。 2. 特定列和所有行。
每当一个列/行被解析时,它应该返回到“原始数组”。
为此,我创建了一个类,将应用我指定的不同解析规则。获取解析规则运作良好。我目前卡在实际文本转换/解析方面。
考虑我有一个名为“regexTextReplace”的解析规则,看起来像这样:
class regexTextReplace
{
private $pattern;
private $replacement;
public function __construct(array $arguments)
{
$this->pattern = $arguments['pattern'];
$this->replacement = $arguments['replacement'];
}
public function apply(array $table, $column = false): array
{
$table = $column ? $table[$column] : $table;
return array_map('self::regex_replace', $table);
}
public function regex_replace(array $table)
{
return preg_replace($this->pattern, $this->replacement, $table);
}
}
这是我如何使用它的方式:
$options = [
'pattern' => '/Trevor/i',
'replacement' => 'Oliver',
];
$engine = new regexTextReplace($options);
$columns = $engine->apply($document->content, 1); //"1" is the specific column.
$columns
返回:
[
{
"row": "My name is Oliver\n"
},
{
"row": "Can you see my?\n"
},
{
"row": "\f"
}
]
这里有两个问题:
- 它成功地应用了解析规则(将Trever替换为Oliver)。但它只返回第一列,而我希望整个原始数组都被转换。
- 如果我从
apply()
方法中删除1
,则会出现以下错误:
Array to string conversion
在下面这一行:
return preg_replace($this->pattern, $this->replacement, $table);
有没有人能指导我正确的方向,以便我可以在任何列或所有列上执行我的解析规则,并将转换后的数据返回到我的原始数组中?
$table = $column ? $table[$column] : $table;
当column
参数为 false 值时,table
将作为数组出现,因此会出现“将数组转换为字符串”的错误。我宁愿使table
的值保持一致,即始终为一个数组,而不是每次调用apply()
时都进行循环。 - Oluwatobi Samuel Omisakin