0

So with Lua I am using it to replace the HTML output from a response page from a Nginx server. In order to make a value="*" HTML tag empty.

The issue is I keep loosing the end of my HTML after Lua replaces the string and makes what ever is between the quotations empty the rest of my HTML on the same line after that is gone.

Lua Code :

body_filter_by_lua_block {
local body = ngx.arg[1] --Put body into local var
local htmlvaluetomakeempty = "id=\"username\" value="
local loginpagematch = ngx.re.match(body, "" .. htmlvaluetomakeempty .. "\"(?:.*)\"") --Search through body to see if our html match is found
if loginpagematch then --If not empty
body = ngx.re.gsub(body, "" .. htmlvaluetomakeempty .. "\"(?:.*)\"", "" .. htmlvaluetomakeempty .. "\"\"") --.. loginpagematch["match"] )
ngx.arg[1] = body
end
}

HTML Code that Lua will be replacing :

<div class="login-fields"><label id="username-lbl" for="username" class="">User Name</label> <input type="text" name="username" id="username" value="test" class="validate-username" size="25"/></div>

After Lua has run and modified the body contents the output looks like this

<div class="login-fields"><label id="username-lbl" for="username" class="">User Name</label> <input type="text" name="username" id="username" value=""/></div>

The problem is this HTML code has also been removed for a unknown reason

class="validate-username" size="25"

It does successfully make id="username" value="" empty but I loose what ever HTML came after it too and I am not sure why.

2
  • 2
    Probably non-greedy match is required in gsub: "\"(?:.*?)\"" Commented Nov 12, 2016 at 17:58
  • Thank's yes you are correct just modified my regex to match that and problem solved :D <3 Commented Nov 12, 2016 at 18:00

1 Answer 1

1

Using regex to manipulate HTML is usually a lost cause. Even whitespace changes in the input can completely break your script. It would be advisable to just use a HTML parsing library such as lua-gumbo.

The following example would find the input#username element and set it's value attribute to the empty string:

local gumbo = require "gumbo"

local input = [[
<div class="login-fields">
    <label id="username-lbl" for="username" class="">User Name</label>
    <input type="text" name="username" id="username" value="test" class="validate-username" size="25"/>
</div>
]]

local document = assert(gumbo.parse(input))
local element = assert(document:getElementById("username"))
element:setAttribute("value", "")
local output = assert(document:serialize())
io.write(output, "\n")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.