简体   繁体   中英

Get input text value from a php string

I have an HTML string inside a PHP variable. The string contains several input fields. How can I get the value of an input field by its ID?

$text = '<html><head></head><body><form action="" method="post"><label>Test</label><input type="text" name="test1" id="test1" value="Value Test" /><label>Test 2</label><input type="text" name="test2" id="test2" value="Value Test2" /></form></body></html>';

One possibility is to use PHP Simple HTML DOM .

Here's an example for finding an input element by ID and printing its value:

<?php

$text = '<html><head></head><body><form action="" method="post"><label>Test</label><input type="text" name="test1" id="test1" value="Value Test" /><label>Test 2</label><input type="text" name="test2" id="test2" value="Value Test2" /></form></body></html>';

// Create DOM from URL or file
$html = str_get_html($text);

foreach($html->find('input') as $element) {
    if($element->id == "test1") {
        echo "Element: #".$element->id." has value: ".$element->value;
    }
}

?>

From what I can tell, you have an HTML string and you want to parse it as HTML, then find an element by its ID.

If you don't want to learn the somewhat initially confusing syntax for XML manipulation or write a probably convoluted regular expression, you could use a tool like phpQuery .

An example would look like:

$html = phpQuery::newDocument($text);
$result = pq($html)->find("#id");

$_POST['test1'] $_POST['test2']

Of course you will need to use these inside of your php code, depending on what you are doing. My example will post the results to your action page.

<?php echo("Your name is ".$_POST['test1']."<BR>Your Age is ".$_POST['test2']); ?>

While regular expressions are not the preferred method for parsing HTML, this is my solution:

<?php
$text = '<html><head></head><body><form action="" method="post"><label>Test</label><input type="text" name="test1" id="test1" value="Value Test" /><label>Test 2</label><input type="text" name="test2" id="test2" value="Value Test2" /></form></body></html>';

$id = 'test1';
preg_match_all("/<input type=\"text\"(.*)id=\"$id\" value=\"(.*?)\"(.*)>/",$text,$matches);

$value = '';
if(isset($matches[2][0])){
    $value = $matches[2][0];
}

echo 'Value: '.$value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM