使用preg_replace查找和替换属性


Finding and replacing attributes using preg_replace

我正试图重做一些有大写字段名称和空间的表单,有数百个字段和50 +表单…我决定尝试编写一个PHP脚本来解析表单的HTML。

现在我有了一个文本区我要把html放到里面我想改变

的所有字段名
name="Here is a form field name"

name="here_is_a_form_field_name"

我如何在一个命令中解析并更改它,使所有的名称标签都是小写的,空格替换为下划线

我假设preg_replace与表达式?

谢谢!

我建议不要使用正则表达式来操作HTML。我将使用DOMDocument,就像下面的

$dom = new DOMDocument();
$dom->loadHTMLFile('filename.html');
// loop each textarea
foreach ($dom->getElementsByTagName('textarea') as $item) {
    // setup new values ie lowercase and replacing space with underscore
    $newval = $item->getAttribute('name');
    $newval = str_replace(' ','_',$newval);
    $newval = strtolower($newval);
    // change attribute
    $item->setAttribute('name', $newval);
}
// save the document
$dom->saveHTML();

另一种选择是使用简单的HTML DOM解析器来完成这项工作-在链接站点

上有一些很好的例子

我同意preg_replace()或更确切地说preg_replace_callback()是适合这项工作的工具,这里有一个如何将其用于您的任务的示例:

preg_replace_callback('/ name="[^"]"/', function ($matches) {
  return str_replace(' ', '_', strtolower($matches[0]))
}, $file_contents);
但是,您应该在之后使用diff工具检查结果,并在必要时对模式进行微调。

我不建议使用DOM解析器的原因是它们通常会阻塞无效的HTML或文件,例如包含用于模板引擎的标记。

这是你的解决方案:

<?php
$nameStr = "Here is a form field name";
while (strpos($nameStr, ' ') !== FALSE) {
    $nameStr = str_replace(' ', '_', $nameStr);
}
echo $nameStr;
?>