跳转到内容

模組:StringReplace

被永久保护的模块
维基百科,自由的百科全书

这是Module:StringReplace当前版本,由Xiplus-abot留言 | 贡献编辑于2020年8月17日 (一) 04:13 (已更改“Module:StringReplace”的保护等级:高風險模板:24829引用<!-- 機器人3 -->([编辑=仅允许模板编辑员和管理员](无限期)[移动=仅允许模板编辑员和管理员](无限期)))。这个网址是本页该版本的固定链接。

(差异) ←上一修订 | 最后版本 (差异) | 下一修订→ (差异)

-- Module for different search and replace operations on strings.
local p = {}

-- Takes one string parameter, and returns the string with all characters with special meaning for Lua patterns escaped with a preceding `%`.
function p.escape_pattern(text)
    -- Replaces each occurrence of any of ().%+-*?[^$ with a `%` and then the character.
    local r = string.gsub(text, "[%(%)%.%%%+%-%*%?%[%^%$]", "%%%1")
    return r
end

-- Returns the first parameter, with all occurrences of the second parameter replaced with the third parameter.
-- All special characters are ignored: {{#invoke:StringReplace|replace_all|test.a%1$foo|%1|bar}} results in `test.abarfoo`.
function p.replace_all(frame)
    local str = frame.args[1]
    local strToFind = frame.args[2]
    local strToreplaceWith = frame.args[3]
    local r = string.gsub(str, p.escape_pattern(strToFind), p.escape_pattern(strToreplaceWith))
    return r
end

p['encode wiki page name'] = function( frame )
	local x = mw.ustring.gsub( 
		frame.args[1] or '', 
		'[\'"&_]', 
		{ 
			["'"] = '&#39;', 
			['"'] = '&#34;', 
			['&'] = '&#38;', 
			['_'] = ' ', 
		} 
	)
	return mw.text.trim( x )
end

return p