【问题标题】:php preg_replace replace array name from inputphp preg_replace 从输入中替换数组名
【发布时间】:2015-09-17 14:27:06
【问题描述】:

你好,如标题所述:
我有这样的输入
<input type="hidden" name="test[]" />
我想做的是从 name 属性中删除 [] ,所以它看起来像这样
<input type="hidden" name="test" />
我想使用正则表达式或 domdocument 来使用它。谢谢您的帮助。
ps:我有很多输入,所以它们将是随机名称属性,而不仅仅是测试。
我正在使用 foreach() 代码从网站获取所有帖子,因此名称属性中包含数组的输入不会被提交,这就是原因。

【问题讨论】:

  • 为什么不像<input type="hidden" name="test">那样直接输入呢?您想为任务使用正则表达式有什么特别的原因吗?
  • jQuery $('[name="test[]"]').attr('name', 'test')
  • 如果你这样做,那么你将不得不调整你的提交处理代码,因为这些字段将成为简单的字符串,而不是数组。
  • 为了能够编写基于 DOMDocument 的解决方案,您应该让我们知道要查找的内容。任何具有name 属性且值以[] 结尾的input
  • 我正在使用 foreach() 代码获取所有帖子

标签: php regex preg-replace domdocument


【解决方案1】:

这是实现您所追求的目标的方法:

$html = "<<YOUR_HTML_STRING>>"
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// Or use $dom->loadHTMLFile($url)

$xpath = new DOMXPath($dom);
$inputs = $xpath->query('//input[@name]'); // Get all <input> tags with name attributes

foreach($inputs as $input) { 
    $name = $input->getAttribute('name'); // Get the name attribute value
    if (substr($name, -2) === "[]") {     // If it ends with [], replace
        $newval = substr($name, 0, $input->getAttribute('name')->length - 2);
        $input->setAttribute('name', $newval);  // Set the new value
    }
}

echo $dom->saveHTML();

IDEONE demo

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    相关资源
    最近更新 更多