WP_MatchesMapRegex

Helper class to remove the need to use eval to replace $matches[] in query strings.

Source

File: wp-includes/class-wp-matchesmapregex.php

class WP_MatchesMapRegex {
	/**
	 * store for matches
	 *
	 * @var array
	 */
	private $_matches;

	/**
	 * store for mapping result
	 *
	 * @var string
	 */
	public $output;

	/**
	 * subject to perform mapping on (query string containing $matches[] references
	 *
	 * @var string
	 */
	private $_subject;

	/**
	 * regexp pattern to match $matches[] references
	 *
	 * @var string
	 */
	public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // Magic number.

	/**
	 * constructor
	 *
	 * @param string $subject subject if regex
	 * @param array  $matches data to use in map
	 */
	public function __construct( $subject, $matches ) {
		$this->_subject = $subject;
		$this->_matches = $matches;
		$this->output   = $this->_map();
	}

	/**
	 * Substitute substring matches in subject.
	 *
	 * static helper function to ease use
	 *
	 * @param string $subject subject
	 * @param array  $matches data used for substitution
	 * @return string
	 */
	public static function apply( $subject, $matches ) {
		$oSelf = new WP_MatchesMapRegex( $subject, $matches );
		return $oSelf->output;
	}

	/**
	 * do the actual mapping
	 *
	 * @return string
	 */
	private function _map() {
		$callback = array( $this, 'callback' );
		return preg_replace_callback( $this->_pattern, $callback, $this->_subject );
	}

	/**
	 * preg_replace_callback hook
	 *
	 * @param array $matches preg_replace regexp matches
	 * @return string
	 */
	public function callback( $matches ) {
		$index = (int) substr( $matches[0], 9, -1 );
		return ( isset( $this->_matches[ $index ] ) ? urlencode( $this->_matches[ $index ] ) : '' );
	}
}

Methods

  • __call — Make private/protected methods readable for backwards compatibility.
  • __construct — constructor
  • __get — Make private properties readable for backwards compatibility.
  • __isset — Make private properties checkable for backwards compatibility.
  • __set — Make private properties settable for backwards compatibility.
  • __unset — Make private properties un-settable for backwards compatibility.
  • _map — do the actual mapping
  • apply — Substitute substring matches in subject.
  • callback — preg_replace_callback hook
  • WP_MatchesMapRegex — constructor

Changelog

Version Description
2.9.0 Introduced.

© 2003–2021 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/classes/wp_matchesmapregex