wp_replace_in_html_tags()
云策文档标注
概述
wp_replace_in_html_tags() 是一个 WordPress 函数,用于仅在 HTML 元素内部替换字符或短语,避免影响标签属性或文本内容外的部分。它基于 wp_html_split() 分割文本,高效处理替换操作。
关键要点
- 函数作用:在 HTML 元素内部(如标签名、属性值)执行替换,不触及元素外的文本。
- 参数:$haystack(必需,要格式化的文本字符串),$replace_pairs(必需,替换对数组,格式为 array('from' => 'to', …))。
- 返回值:返回格式化后的字符串。
- 优化:当替换对数量为 1 时,函数会优化循环以提高性能。
- 相关函数:依赖 wp_html_split() 分割 HTML 元素,被 wpautop() 和 WP_Embed::autoembed() 使用。
- 版本历史:从 WordPress 4.2.3 版本引入。
代码示例
// 替换文本中的“products”为“services”
$content = 'Welcome to our website! We offer a variety of products.';
$replacements = array(
'products' => 'services', // 将“products”替换为“services”
);
$new_content = wp_replace_in_html_tags($content, $replacements);
echo $new_content;
// 输出:Welcome to our website! We offer a variety of services.
原文内容
Replaces characters or phrases within HTML elements only.
Parameters
$haystackstringrequired-
The text which has to be formatted.
$replace_pairsarrayrequired-
In the form array(
'from'=>'to', …).
Source
function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
// Find all elements.
$textarr = wp_html_split( $haystack );
$changed = false;
// Optimize when searching for one item.
if ( 1 === count( $replace_pairs ) ) {
// Extract $needle and $replace.
$needle = array_key_first( $replace_pairs );
$replace = $replace_pairs[ $needle ];
// Loop through delimiters (elements) only.
for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
if ( str_contains( $textarr[ $i ], $needle ) ) {
$textarr[ $i ] = str_replace( $needle, $replace, $textarr[ $i ] );
$changed = true;
}
}
} else {
// Extract all $needles.
$needles = array_keys( $replace_pairs );
// Loop through delimiters (elements) only.
for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
foreach ( $needles as $needle ) {
if ( str_contains( $textarr[ $i ], $needle ) ) {
$textarr[ $i ] = strtr( $textarr[ $i ], $replace_pairs );
$changed = true;
// After one strtr() break out of the foreach loop and look at next element.
break;
}
}
}
}
if ( $changed ) {
$haystack = implode( $textarr );
}
return $haystack;
}
Changelog
| Version | Description |
|---|---|
| 4.2.3 | Introduced. |
Skip to note 3 content
وردپرس ایرانی
Replace “products” with “services” in text
$content = 'Welcome to our website! We offer a variety of products.'; $replacements = array( 'products' => 'services', // Replace "products" with "services" ); $new_content = wp_replace_in_html_tags($content, $replacements); echo $new_content;Output:
Welcome to our website! We offer a variety of services.
Skip to note 4 content
وردپرس ایرانی
Add Attributes to Existing Elements:
$content = ''; // Missing alt attribute $replacements = array( ' '<img alt="description of the image"', // Add alt attribute ); $new_content = wp_replace_in_html_tags($content, $replacements); echo $new_content;