Skip to content

Instantly share code, notes, and snippets.

@chernomyrdin
Created May 27, 2014 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chernomyrdin/3d7be25455fcfafc0b71 to your computer and use it in GitHub Desktop.
Save chernomyrdin/3d7be25455fcfafc0b71 to your computer and use it in GitHub Desktop.
Replace substring, append some string demo for preg_replace_callback
<?php
class Replacer {
private static $__instance;
private $regex = '';
private $append = '';
private $replace = array(
'ул' => 'улица',
'ш' => 'шоссе',
'пр' => 'проспект',
'пер' => 'переулок',
'бул' => 'бульвар',
);
public function __construct (Array $replace = array()) {
if (!empty($replace)) {
$this->replace = $replace;
}
$this->regex .= '/\s*(';
$this->regex .= implode(
'|',
array_map(
'preg_quote',
array_keys($this->replace)
)
);
$this->regex .= ')\.\s*/ui';
}
private function __replace_callback ($matches) {
if (isset($this->replace[ $matches[1] ])) {
$this->append = ' ' . $this->replace[ $matches[1] ];
}
return '';
}
private function append ($output) {
$output .= $this->append;
$this->append = '';
return $output;
}
public function replace ($input) {
return $this->append( preg_replace_callback(
$this->regex,
array($this, "__replace_callback"),
$input
) );
}
public static function str ($input) {
if (empty(self::$__instance)) {
self::$__instance = new Replacer;
}
return self::$__instance->replace($input);
}
}
foreach (array("ул. Ленина","Торфяная улица","Моссковское ш.") as $input) {
echo $input, " => ", Replacer::str($input), PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment