Dizzi
Dizzi

Reputation: 747

Remove an <input> tag with a specified name attribute

I want to replace a string such as:

<input type="hidden" name="id" value="12345" />

but the problem I have is that the value's value (12345) is different everytime so how can I do what I'm trying to do? ..I'm guessing regex' but haven't a clue.

Upvotes: 0

Views: 994

Answers (2)

mickmackusa
mickmackusa

Reputation: 47863

Reliably and intuitively target and destroy the first occurring HTML input element with the qualifying name attribute using DomDocument and XPath.

Code: (Demo)

$html = <<<HTML
<form>
<input type="hidden" name="id" value="12345" />
</form>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$input = (new DOMXPath($dom))
    ->query('//input[@name="id"]')
    ->item(0);
$input->parentNode->removeChild($input);
echo $dom->saveHTML();

Output:

<form>

</form>

Upvotes: 0

delphist
delphist

Reputation: 4539

preg_replace('/\<input type="hidden" name="id" value="[0-9]+" \/\>/is', '', $source)

Upvotes: 6

Related Questions