Tiago Castro Tiago Castro - 1 year ago 96
PHP Question

Remove string direct from file without replace the entity file in PHP

Im trying to remove string from file by seeking its position then remove. I dont want to store the entity file in a string than replace. I need to replace it directy on the file, is there any way I could do this?

I have to find the "#" then remove until I find the next.

Remove #2 data from myfile.txt


After remove:


How can I do this?

Answer Source

PHP doesn't provide any way to directly manipulate file contents. You have to read into a PHP variable, then write back out to the file.

In C on a POSIX system you can do it using mmap().

int fd = open("myfile.txt", O_RDWR);
struct stat stat_buf;
fstat(fd, &stat_buf);
size_t len = stat_buf.st_size;
char *contents = mmap(NULL, len, PROT_WRITE, MAP_SHARED, fd, 0);
char *num2 = strstr(contents, "#2"); // Find #2
char *num3 = strstr(num2, "#3"); // Find #3 after #2
memmove(num3, num2, len-(num3-contents)); // Shift everything from #3 over
memset(contents + len - (num3 - num2), num3 - num2); // Zero the end of the file
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download