因此,我有一个嵌套数组,它模拟一个表布局(列和行):
{
"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“是列,然后在每一列下,可以有任意数量的行。
现在我正在尝试这样做,这样我的用户就可以对以下两种方法执行各种解析规则:
每当分析了列/行时,就应该将其返回到“原始数组”。
为此,我创建了一个类,它将应用我指定的不同解析规则。获得解析规则很好。目前,我仍然停留在实际的文本转换/解析方面。
假设我有一个名为"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"
}
]这里有两个问题:
1方法中删除apply(),则会得到以下错误:Array to string conversion在下面一行:
return preg_replace($this->pattern, $this->replacement, $table);谁能引导我朝着正确的方向前进,这样我就可以对任何列或所有列执行我的解析规则,并将转换后的数据返回到我的原始数组中?
发布于 2019-05-16 08:43:02
我将重写apply函数来循环整个表,如果没有设置column参数,或者如果它与当前的表列匹配,则处理每个列:
public function apply(array $table, $column = false): array
{
$out = array();
foreach ($table as $col => $rows) {
if ($column === false || $col == $column) {
$out[$col] = array_map('self::regex_replace', $rows);
}
else {
$out[$col] = $rows;
}
}
return $out;
}发布于 2019-05-16 08:45:41
您可以重写您的apply方法如下:
public function apply(array $table, $columns = false): array
{
$columns = $columns === false ? array_keys($table) : (array)$columns;
return array_map(function ($column) use ($table, $columns) {
return in_array($column, $columns) ? array_map('self::regex_replace', $table[$column]) : $table[$column];
}, array_keys($table));
}可以传递单个列或列数组,也可以传递nothing (false)来指定要调整的列。
发布于 2019-05-16 08:24:01
只需循环它并对所有子数组执行正则表达式:
$content = json_decode($json, true);
$options = [
'pattern' => '/Trevor/i',
'replacement' => 'Oliver',
];
$engine = new regexTextReplace($options);
foreach($content as $key => $v){
$columns[$key] = $engine->apply($content, $key);
}
var_dump($columns);工作演示:
在"PHP“端循环而不是在类中循环的好处是,您仍然可以将regex应用于一个或两个子数组。
如果在类中循环,那么需要传递更多的参数来限制循环或执行某种类型的数组切片。
https://stackoverflow.com/questions/56163950
复制相似问题