troubleshooting Question

Removing unwanted whitespace and funny characters from end of scripts with C

Avatar of hankknight
hankknightFlag for Canada asked on
18 Comments3 Solutions560 ViewsLast Modified:

I have a directory (with many sub-directories) containing lots of PHP scripts with unwanted trailing characters.

For example:


The whitespace and newlines are causing me greif.

So if ANY .php file contains ANYTHING after the last ?> that is NOT 0-9 or a-Z then I want EVERYTHING after the last ?> to be REMOVED.

How can I do this for all scripts in a directory and its sub-directories (recursively)?  Keep in mind that some PHP scripts contain several <? and ?> and I only want to check for the very last ?>

I thought that maybe the C script below could be modified to do this.

Can anyone make the modifications for me?

 * Released under GNU GPL
 * created by Strychnine
 * this program reads the file given in argv[1] and
 * writes all comments to data, then checks the comment
 * for argv[2] the program outputs all the charaters in
 * the file unless it is a comment that contains argv[2]
 * to compile: # gcc thisfile.c -o rmcom
 * to run: # ./rmcom 'filename' 'Search String'
 * use the program in conjunction with the `find` command's
 * -exec switch to edit multiple files at once, or use a bash script

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
 if(argc > 2) {
  FILE* fp = fopen(argv[1], "r");
  char data[32767];
  char buf;
  char buf2;
  int x=0;
  while(!feof(fp)) {
   if(buf == '/') {
    if(buf2 == '*') {
     while(!feof(fp)) {
      if(data[x] == '/' && data[(x-1)] == '*') {
       if(!strstr(data, argv[2])) {
        printf("/*%s", data);
    } else {
     printf("%c%c", buf, buf2);
   } else {
    printf("%c", buf);
 } else {
  printf("usage: uncomment <string to find> <filename>");
 return 0;

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 3 Answers and 18 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 3 Answers and 18 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros