home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / class-wp-matchesmapregex.php < prev    next >
Encoding:
PHP Script  |  2017-07-26  |  1.8 KB  |  92 lines

  1. <?php
  2. /**
  3.  * WP_MatchesMapRegex helper class
  4.  *
  5.  * @package WordPress
  6.  * @since 4.7.0
  7.  */
  8.  
  9. /**
  10.  * Helper class to remove the need to use eval to replace $matches[] in query strings.
  11.  *
  12.  * @since 2.9.0
  13.  */
  14. class WP_MatchesMapRegex {
  15.     /**
  16.      * store for matches
  17.      *
  18.      * @var array
  19.      */
  20.     private $_matches;
  21.  
  22.     /**
  23.      * store for mapping result
  24.      *
  25.      * @var string
  26.      */
  27.     public $output;
  28.  
  29.     /**
  30.      * subject to perform mapping on (query string containing $matches[] references
  31.      *
  32.      * @var string
  33.      */
  34.     private $_subject;
  35.  
  36.     /**
  37.      * regexp pattern to match $matches[] references
  38.      *
  39.      * @var string
  40.      */
  41.     public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
  42.  
  43.     /**
  44.      * constructor
  45.      *
  46.      * @param string $subject subject if regex
  47.      * @param array  $matches data to use in map
  48.      */
  49.     public function __construct($subject, $matches) {
  50.         $this->_subject = $subject;
  51.         $this->_matches = $matches;
  52.         $this->output = $this->_map();
  53.     }
  54.  
  55.     /**
  56.      * Substitute substring matches in subject.
  57.      *
  58.      * static helper function to ease use
  59.      *
  60.      * @static
  61.      *
  62.      * @param string $subject subject
  63.      * @param array  $matches data used for substitution
  64.      * @return string
  65.      */
  66.     public static function apply($subject, $matches) {
  67.         $oSelf = new WP_MatchesMapRegex($subject, $matches);
  68.         return $oSelf->output;
  69.     }
  70.  
  71.     /**
  72.      * do the actual mapping
  73.      *
  74.      * @return string
  75.      */
  76.     private function _map() {
  77.         $callback = array($this, 'callback');
  78.         return preg_replace_callback($this->_pattern, $callback, $this->_subject);
  79.     }
  80.  
  81.     /**
  82.      * preg_replace_callback hook
  83.      *
  84.      * @param  array $matches preg_replace regexp matches
  85.      * @return string
  86.      */
  87.     public function callback($matches) {
  88.         $index = intval(substr($matches[0], 9, -1));
  89.         return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );
  90.     }
  91. }
  92.