Skip to content

Instantly share code, notes, and snippets.

@Zemistr
Forked from steinbauer/changeTextFromParameters.php
Last active February 3, 2016 09:57
Show Gist options
  • Save Zemistr/698e62ef846b5110fbb5 to your computer and use it in GitHub Desktop.
Save Zemistr/698e62ef846b5110fbb5 to your computer and use it in GitHub Desktop.
Modifikace textu
<?php
$changeParameters = [
"vyrobce" => "Canon",
"garance_tisku" => "5000 stran",
"kompatibilita" => "Canon XYZ"
];
$input = "Vysoce kvalitní toner určený pro laserové tiskárny[ [vyrobce]][ s garancí tisku [garance_tisku] při 5% pokrytí][ a kompatibilní s [kompatibilita]].";
/*
-> typ zapisu vztupního textu:
OKOLO [ ZONA [KEY] ZONA ] OKOLO ,
nebo OKOLO [ ZONA [KEY]] OKOLO,
nebo OKOLO [[KEY]] OKOLO
->Vyhodnocení:
Když empty(KEY), musí zmizet všechno v okrajových závorkách (včetně),
když !empty(KEY) /else varianta prvn9ho/, nahradí [KEY] hodnotou z pole a osatní text ponechá.
-> PS:
rychlý nástřel reg. výrazu, zdřejmě nevhodně postaveného: https://regex101.com/r/pK7eE6/3
*/
$output = modify_text($input, $changeParameters); //volani
function modify_text($input, array $changeParameters) {
$output = preg_replace_callback(
'~\[([^\[]*)\[([^\]]*)]([^\]]*)]~',
function ($match) use ($changeParameters) {
list(, $prefix, $key, $suffix) = $match;
if (empty($changeParameters[$key])) {
return '';
}
return $prefix . $changeParameters[$key] . $suffix;
},
$input
);
$output = preg_replace('~\s+~', ' ', $output);
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment