php - 获取 html 输入元素的值作为 php 字符串

标签 php regex html-parsing

我有一个 html 文件作为字符串加载到 php 中,我需要获取 HTML 字符串中输入元素的值。有人可以帮助我构建一个函数,该函数采用输入元素的名称并返回其值吗?

这是我想要执行的功能的示例:

function getVal($name){

    $htmlStr = "<form action = \"action.php\"><input type=\"hidden\" name=\"command\" value=\"123456\">
                <input type=\"hidden\" name=\"quantity\" value=\"1\">
                <input type=\"hidden\" name=\"user_mode\" value=\"1\">
                <input type=\"hidden\" name=\"stock\" value=\"-1255303070\">
                <input type=\"hidden\" name=\"id\" value="429762082">
                <input type=\"hidden\" name=\"pidm\" value=\"2\"></form>";

            // I'd like to get the value of $name here probably using preg_match     

            return $value; //returns 123456

        }

$val = getVal("命令");//val 应为 123456。

有什么伊达吗?谢谢

最佳答案

这是一个 DOM 示例:

$html = "<form action = \"action.php\">
  <input type=\"hidden\" name=\"command\" value=\"123456\">
  <input type=\"hidden\" name=\"quantity\" value=\"1\">
  <input type=\"hidden\" name=\"user_mode\" value=\"1\">
  <input type=\"hidden\" name=\"stock\" value=\"-1255303070\">
  <input type=\"hidden\" name=\"id\" value=\"429762082\">
  <input type=\"hidden\" name=\"pidm\" value=\"2\">
</form>";

$document = new DOMDocument();
$document->loadHTML($html);

$inputs = $document->getElementsByTagName("input");

foreach ($inputs as $input) {
  if ($input->getAttribute("name") == "id") {
    $value = $input->getAttribute("value");
  }
}

echo $value;

关于php - 获取 html 输入元素的值作为 php 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13591126/

相关文章:

php - preg_match php 错误 - 找不到结束分隔符 '^'

mysql - 用于检查字符串开头或结尾处是否有空格的 RegEx 模式

Python、Selenium、BS4 - 导航到下一页

php - 简单的 html dom file_get_html 不工作 - 有什么解决方法吗?

php - 如何发现sql注入(inject)漏洞?

php - 如何使用 ssp.class.php 连接两个表

PHP正则表达式;在 WordPress 短代码中提取第一个匹配的 ID

python - BeautifulSoup 获得标签.id

PHP寻找一个从字符串中获取值的函数

java - 正则表达式匹配[[维基百科:Manual of Style#Links|]] # in java