Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php preg_替换输入中的数组名称_Php_Regex_Preg Replace_Domdocument - Fatal编程技术网

php preg_替换输入中的数组名称

php preg_替换输入中的数组名称,php,regex,preg-replace,domdocument,Php,Regex,Preg Replace,Domdocument,您好,如标题所述: 我有一个类似这样的输入我想做的是从name属性中删除[],使其看起来像这样 我想使用regex或domdocument来使用它。谢谢你的帮助。 ps:我有很多输入,所以它们将是随机名称属性,而不仅仅是测试。 我正在使用foreach()代码从网站获取所有帖子,因此在name属性中使用数组的输入不会被提交,这就是为什么。以下是一种实现所需内容的方法: $html = "<<YOUR_HTML_STRING>>" $dom = new DOMDocumen

您好,如标题所述:
我有一个类似这样的输入

我想做的是从name属性中删除[],使其看起来像这样

我想使用regex或domdocument来使用它。谢谢你的帮助。
ps:我有很多输入,所以它们将是随机名称属性,而不仅仅是测试。

我正在使用foreach()代码从网站获取所有帖子,因此在name属性中使用数组的输入不会被提交,这就是为什么。

以下是一种实现所需内容的方法:

$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();
$html=“”
$dom=新的DOMDocument('1.0','UTF-8');
$dom->loadHTML($html,LIBXML\u html\u noimpled | LIBXML\u html\u NODEFDTD);
//或者使用$dom->loadHTMLFile($url)
$xpath=newdomxpath($dom);
$inputs=$xpath->query('//input[@name]');//获取具有名称属性的所有标记
foreach($inputs作为$input){
$name=$input->getAttribute('name');//获取name属性值
如果(substr($name,-2)==“[]”{//如果以[]结尾,则替换
$newval=substr($name,0,$input->getAttribute('name')->length-2);
$input->setAttribute('name',$newval);//设置新值
}
}
echo$dom->saveHTML();

请参见

为什么不直接键入它,就像在
中一样?您希望使用正则表达式执行任务的任何特定原因?jQuery
$('[name=“test[]”]').attr('name','test')
如果您这样做,那么您必须调整提交处理代码,因为这些字段将变成简单的字符串,而不是数组。要编写基于DOMDocument的解决方案,您应该让我们知道要查找什么。任何具有
名称
属性且其值以
[]
结尾的
输入
?我使用foreach()代码获取所有帖子