Greg Alexander
Greg Alexander

Reputation: 1222

Finding and replacing attributes using preg_replace

I am trying to redo some forms that have uppercase field names and spaces, there are hundreds of fields and 50 + forms... I decided to try to write a PHP script that parses through the HTML of the form.

So now I have a textarea that I will post the html into and I want to change all the field names from

name="Here is a form field name"

to

name="here_is_a_form_field_name"

How in one command could I parse through and change it so all in the name tags would be lowercase and spaces replace with underscores

I am assuming preg_replace with an expression?

Thanks!

Upvotes: 1

Views: 1378

Answers (3)

Manse
Manse

Reputation: 38147

I would suggest not using regex for manipulation of HTML .. I would use DOMDocument instead, something like the following

$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();

An alternative would be to use something like Simple HTML DOM Parser for the job - there are some good examples on the linked site

Upvotes: 8

Pawan Thakur
Pawan Thakur

Reputation: 591

This is your Solution:

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

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

Upvotes: 0

AndreKR
AndreKR

Reputation: 33678

I agree that preg_replace() or rather preg_replace_callback() is the right tool for the job, here's an example of how to use it for your task:

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

You should, however, check the results afterwards using a diff tool and fine-tune the pattern if necessary.

The reason why I would recommend against a DOM parser is that they usually choke on invalid HTML or files that contain for example tags for templating engines.

Upvotes: 1

Related Questions