<?php
$json = '{
"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 Trevor?\n"
},
{
"row": "\f"
}
],
"3": [
{
"row": "Some text on the third column. First row."
},
{
"row": "\f"
}
]
}';
$content = json_decode($json, true);
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
{
$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;
}
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($content, 1);
print_r($columns);
$options = [
'pattern' => '/Some/i',
'replacement' => 'A lot of',
];
$engine = new regexTextReplace($options);
$columns = $engine->apply($content);
print_r($columns);
preferences:
65.87 ms | 402 KiB | 5 Q