_deep_replace()
云策文档标注
概述
_deep_replace() 是 WordPress 核心函数,用于执行深度字符串替换操作,确保 $search 中的值不再出现在结果中。它通过循环替换来移除嵌套值,避免 str_replace 可能导致的残留问题。
关键要点
- 函数执行深度替换,直到 $search 值完全消失,防止嵌套值残留。
- 参数 $search 可以是字符串或数组,用于指定要搜索的针;$subject 是待替换的字符串。
- 返回替换后的字符串,确保 $search 内容被彻底移除。
代码示例
function _deep_replace( $search, $subject ) {
$subject = (string) $subject;
$count = 1;
while ( $count ) {
$subject = str_replace( $search, '', $subject, $count );
}
return $subject;
}注意事项
- 与 str_replace 不同,_deep_replace 能处理嵌套情况,例如 $subject = '%0%0%0DDD', $search = '%0D' 时,返回空字符串而非 '%0%0DD'。
- 该函数自 WordPress 2.8.1 版本引入,常用于 URL 清理和重定向消毒等场景。
原文内容
Performs a deep string replace operation to ensure the values in $search are no longer present.
Description
Repeats the replacement operation until it no longer replaces anything to remove “nested” values e.g. $subject = ‘%0%0%0DDD’, $search =’%0D’, $result =” rather than the ‘%0%0DD’ that str_replace would return
Parameters
$searchstring|arrayrequired-
The value being searched for, otherwise known as the needle.
An array may be used to designate multiple needles. $subjectstringrequired-
The string being searched and replaced on, otherwise known as the haystack.
Source
function _deep_replace( $search, $subject ) {
$subject = (string) $subject;
$count = 1;
while ( $count ) {
$subject = str_replace( $search, '', $subject, $count );
}
return $subject;
}
Changelog
| Version | Description |
|---|---|
| 2.8.1 | Introduced. |