class@anonymous
云策文档标注
概述
本文档介绍了一个匿名类,它扩展自 WP_HTML_Tag_Processor,用于在 HTML 文档中操作当前标记。该类提供了获取标记跨度、插入文本、移除标记和替换富文本的方法。
关键要点
- 匿名类扩展自 WP_HTML_Tag_Processor,用于处理 HTML 标记。
- 提供 get_span 方法获取当前标记的 WP_HTML_Span 对象。
- 提供 insert_before 和 insert_after 方法在当前标记前后插入文本。
- 提供 remove 方法移除当前标记。
- 提供 replace_rich_text 方法替换标签开闭符之间的富文本内容。
- 相关类 WP_HTML_Tag_Processor 是 WordPress 核心类,用于修改 HTML 文档中匹配查询的标签属性。
代码示例
Source $processor = new class( $buffer ) extends WP_HTML_Tag_Processor {
/**
* Gets the span for the current token.
*
* @return WP_HTML_Span Current token span.
*/
private function get_span(): WP_HTML_Span {
// Note: This call will never fail according to the usage of this class, given it is always called after ::next_tag() is true.
$this->set_bookmark( 'here' );
return $this->bookmarks['here'];
}
/**
* Inserts text before the current token.
*
* @param string $text Text to insert.
*/
public function insert_before( string $text ) {
$this->lexical_updates[] = new WP_HTML_Text_Replacement( $this->get_span()->start, 0, $text );
}
/**
* Inserts text after the current token.
*
* @param string $text Text to insert.
*/
public function insert_after( string $text ) {
$span = $this->get_span();
$this->lexical_updates[] = new WP_HTML_Text_Replacement( $span->start + $span->length, 0, $text );
}
/**
* Removes the current token.
*/
public function remove() {
$span = $this->get_span();
$this->lexical_updates[] = new WP_HTML_Text_Replacement( $span->start, $span->length, '' );
}
};
原文内容
Methods
| Name | Description |
|---|---|
| class@anonymous::get_span | Gets the span for the current token. |
| class@anonymous::insert_after | Inserts text after the current token. |
| class@anonymous::insert_before | Inserts text before the current token. |
| class@anonymous::remove | Removes the current token. |
| class@anonymous::replace_rich_text | Replace the rich text content between a tag opener and matching closer. |
Source
$processor = new class( $buffer ) extends WP_HTML_Tag_Processor {
/**
* Gets the span for the current token.
*
* @return WP_HTML_Span Current token span.
*/
private function get_span(): WP_HTML_Span {
// Note: This call will never fail according to the usage of this class, given it is always called after ::next_tag() is true.
$this->set_bookmark( 'here' );
return $this->bookmarks['here'];
}
/**
* Inserts text before the current token.
*
* @param string $text Text to insert.
*/
public function insert_before( string $text ) {
$this->lexical_updates[] = new WP_HTML_Text_Replacement( $this->get_span()->start, 0, $text );
}
/**
* Inserts text after the current token.
*
* @param string $text Text to insert.
*/
public function insert_after( string $text ) {
$span = $this->get_span();
$this->lexical_updates[] = new WP_HTML_Text_Replacement( $span->start + $span->length, 0, $text );
}
/**
* Removes the current token.
*/
public function remove() {
$span = $this->get_span();
$this->lexical_updates[] = new WP_HTML_Text_Replacement( $span->start, $span->length, '' );
}
};