skip to Main Content

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

2

Answers


  1. Use the following to code to get the file names in an array from string.

    <?php
    $string = "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";
    preg_match_all('#bhttps?://[^,s()<>]+(?:([wd]+)|([^,[:punct:]s]|/))#', $string, $match);
    $all_filenames = array();
    for ($i = 0; $i < count ($match[0]); $i++)
    {
        $url = $match[0][$i];
        $filename = substr($url, strrpos($url, '/') + 1);
        array_push($all_filenames, $filename);
    }
    echo "<pre>";
    print_r($all_filenames); 
    echo "</pre>";
    ?>
    
    Login or Signup to reply.
  2. 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);
                }
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search