questions

Extract Filename from a String and use it to Delete the WP File in PHP

Rate this post

How can we check if a string, which contains words has a URL that starts with something like https://example.com/wp-content/uploads/Chat/...

If it matches, then extract the child directory and the filname filename, and then delete the file from server.

For example, if a string is of form: "Bla Bla Bla https://example.com/wp-content/uploads/Chat/IMG/Abc.pdf Bla Bla Bla Bla"

then check if the string contains a URL that starts with https://example.com/wp-content/uploads/Chat/

If it does, then extract the directory (IMG) it can be IMG or Video or Document, and end filename that is Abc.pdf

Then delete the file Abc.pdf

Here’s What I tried

I used a regex expression, in PHP to match the starting URL. However I cant figure out how to extract the filename from it, as filename is in the string, and then how to delete the file.

^https:\/\/example\.com\/wp-content\/uploads\/Chat

 

✔️Solution:

You were already half way their. Regex is the only logical way to move forward in it.

Using regex, I search for the beginning url

Then I assign the last directory and file name to a variable $File.

$File[1] = Last Directory

$File[3] = FileName

        $message = "Bla Bla Bla https://example.com/wp-content/uploads/Chat/IMG/Abc.pdf Bla Bla Bla Bla Bla https://example.com/wp-content/uploads/Chat/IMG/XYZ.pdf Bla Bla Bla Bla";
        $Match = false;
        if(preg_match('/https:\/\/milyin.com\/wp-content\/uploads\/Chat\/(IMG|Video|Document)(\/)([0-9A-Za-z_-]+\.[A-Za-z]{3,4})/', $message)){
            $Match = true;
            preg_match('/https:\/\/example.com\/wp-content\/uploads\/Chat\/(IMG|Video|Document)(\/)([0-9A-Za-z_-]+\.[A-Za-z]{3,4})/', $message, $File);
            if(isset($File[1]) && isset($File[3])){
                $FileName = ABSPATH . "wp-content/uploads/Chat/" . $File[1] . '/' . $File[3];
                unlink($FileName);
            }
        }

Leave a Reply

Your email address will not be published.

Back to top button