<?php
$document = json_decode(<<<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?\\n"
},
{
"row": "\\f"
}
],
"3": [
{
"row": "Some text on the third column. First row. Trevor btw."
},
{
"row": "\\f"
}
]
}
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, $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));
}
public function regex_replace(array $table)
{
return preg_replace($this->pattern, $this->replacement, $table);
}
}
$options = [
'pattern' => '/Trevor/i',
'replacement' => 'Oliver',
];
$engine = new regexTextReplace($options);
print_r('======= ONLY COLUMN 1 =======' . PHP_EOL . PHP_EOL);
print_r($engine->apply($document, 1));
print_r(PHP_EOL . PHP_EOL . '======= COLUMNS 1 & 3 =======' . PHP_EOL . PHP_EOL);
print_r($engine->apply($document, [1, 3]));
print_r(PHP_EOL . PHP_EOL . '======= ALL TABLE =======' . PHP_EOL . PHP_EOL);
print_r($engine->apply($document));
preferences:
46.03 ms | 402 KiB | 5 Q