使用sed重写代码(搜索和替换)

I have hundreds of statements like this in a codebase:

if ($stmt->execute(array(/* parameters */))) {
    $att = $stmt->fetchAll(); /* or any other fetch method */
} else {
    throw new DatabaseException(__METHOD__.": failed");
}

Another variant, which does not fetch any data:

if (!$stmt->execute(array(/* parameters */))) {
    throw new DatabaseException("Error");
}

In both cases, the if ... and throw ... should be removed, i.e. the first snippet would be reduced to:

$stmt->execute(array(/* parameters */));
$att = $stmt->fetchAll(); /* or any other fetch method */

and the second:

$stmt->execute(array(/* parameters */));

Note:

  • array(/* parameters */) may be missing if there are no parameters present.
  • $stmt may have another name (like $foo).

Background: Instead of a lot of custom code, I would like to have PDO throw an Exception when an error occurs. Currently it is set to silently ignore errors, which needs a lot of additional checks...

Note: If this is too complex for sed or similiar tools, I will accept an answer which points to another tool that could help avoid rewriting all those statements by hand.

$> cat codes.txt

if ($stmt->execute(array(/* parameters */))) {
  $att = $stmt->fetchAll(); /* or any other fetch method */
} else {
  throw new DatabaseException(__METHOD__.": failed");
}
if (!$stmt->execute(array(/* parameters */))) {
  throw new DatabaseException("Error");
}

$> perl -p0777e 's:(if \(\s*\!?\s*)(.*?)(\s*\)\s*\{\s*)((.*?)\s*\}\s*else\s*\{\s*)?throw .*?;\s*\}:$2;
$5:g' codes.txt

$stmt->execute(array(/* parameters */));
$att = $stmt->fetchAll(); /* or any other fetch method */
$stmt->execute(array(/* parameters */));

  1. This solution is only for non-nested {} codes.
  2. For nested {}, it will be very difficult, and I do not think regexp could do. You'll need to write a sort of parser for that.