Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Filling Form Input non-intrusively Using DOM or REGEX

Tags:

dom

regex

forms

php

I'm working on a user authentication system. Because I want it to be as customizable and flexible as possible, I do not want to mix PHP with HTML. I have developed a simple template engine which works just fine (uses pure HTML files for layout only). However I have a problem with forms. In some cases (such as when input validation fails) I would like to make them remember the previously entered data. I use output buffering to display the end HTML to the user and so I have the whole layout stored in a string. What I'm trying to do in this string is find specific HTML elements (by their ID attributes) and subsequently change their values. I know how to solve the problem in case text or password fields, but I'll also be using comboboxes and those need to be handled differently. I was thinking of using DOM to achieve the task, but so far my attempts have not been successful.

So here's what I want to do:

  1. find an element by its ID in the string using DOM change the element appropriately replace the old element with the new one in the string, but keep the rest of the string unchanged

Here's a simple (not working) snippet (should be enough to illustrate the problem):

<?php
$content = "<input id=\"id\" name=\"name\" type=\"text\" value=\"\" />";
$itemid = "id";
$dom = new DOMDocument();
$dom->loadXML($content);
$item = $dom->getElementById($itemid);
if($item)
{
$value = "New Value";
$newitem = $item;
$newitem->setAttribute('value', $value);
$item = $item->saveXML();
$newitem = $newitem->saveXML();
$content = str_replace($item, $newitem, $content);
}
echo $content;
?>

Or should I go with REGEX instead?

Thank you so much!

like image 830
Matej Golian Avatar asked Feb 03 '26 08:02

Matej Golian


1 Answers

This is easily done with Simple dom html parser.

$data = $content = "<input id=\"id\" name=\"name\" type=\"text\" value=\"\" />";
$html = str_get_html($data);
$html->find("input[id='id']",0)->value = "New Value";
echo $html->save();

Cant be easier.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!