Created
May 27, 2014 14:30
-
-
Save chernomyrdin/3d7be25455fcfafc0b71 to your computer and use it in GitHub Desktop.
Replace substring, append some string demo for preg_replace_callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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