繁体   English   中英

使用preg_replace查找和替换属性

[英]Finding and replacing attributes using preg_replace

我正在尝试重做一些具有大写字段名和空格的表单,有数百个字段和50多个表单...我决定尝试编写一个通过表单HTML进行解析的PHP脚本。

所以现在我有一个textarea,我将把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();

一种替代方法是使用诸如Simple HTML DOM Parser之类的工具进行工作-链接站点上有一些很好的示例

我同意preg_replace()或更确切地说preg_replace_callback()是这项工作的正确工具,这是一个如何在任务中使用它的示例:

preg_replace_callback('/ name="[^"]"/', function ($matches) {
  return str_replace(' ', '_', strtolower($matches[0]))
}, $file_contents);

但是,您之后应使用差异工具检查结果,并在必要时微调图案。

我之所以反对DOM解析器,是因为它们通常会阻塞无效的HTML或包含例如模板引擎标记的文件。

这是您的解决方案:

<?php
$nameStr = "Here is a form field name";

while (strpos($nameStr, ' ') !== FALSE) {
    $nameStr = str_replace(' ', '_', $nameStr);
}
echo $nameStr;
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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