类文档

WP_MatchesMapRegex

💡 云策文档标注

概述

WP_MatchesMapRegex 是一个辅助类,用于在查询字符串中替换 $matches[] 引用,避免使用 eval 函数,提高安全性和性能。它通过正则表达式匹配和回调函数实现映射。

关键要点

  • 核心功能:安全替换查询字符串中的 $matches[] 引用,无需 eval。
  • 主要方法:包括构造函数 __construct、静态方法 apply、私有方法 _map 和回调方法 callback。
  • 属性:$_matches 存储匹配数据,$_subject 存储查询字符串,$_pattern 定义正则模式,$output 存储映射结果。
  • 使用场景:适用于 WordPress 开发中处理查询字符串替换,如重写规则或 URL 解析。

代码示例

// 使用静态方法 apply 进行替换
$subject = 'page=$matches[1]&id=$matches[2]';
$matches = array(1 => 'about', 2 => '123');
$result = WP_MatchesMapRegex::apply($subject, $matches);
// $result 输出: 'page=about&id=123'

注意事项

  • $_pattern 默认匹配 $matches[数字] 格式,数字从1开始,可自定义。
  • callback 方法会使用 urlencode 对替换值进行编码,确保 URL 安全。
  • 类自 WordPress 2.9.0 版本引入,需注意版本兼容性。

📄 原文内容

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

Methods

Name Description
WP_MatchesMapRegex::__construct constructor
WP_MatchesMapRegex::_map do the actual mapping
WP_MatchesMapRegex::apply Substitute substring matches in subject.
WP_MatchesMapRegex::callback preg_replace_callback hook

Source

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 ) {
		$result = new WP_MatchesMapRegex( $subject, $matches );
		return $result->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 ] ) : '' );
	}
}

Changelog

Version Description
2.9.0 Introduced.