Search code examples
phpurlrelative-path

How to remove part of a url?


Trying to turn this:

href="/wp-content/themes/tray/img/celebrity_photos/photo.jpg"

into:

href="/img/celebrity_photos/photo.jpg"

So I'm simply trying to remove /wp-content/themes/tray/ from the url.

Here's the plug in's PHP code that builds a variable for each anchor path:

$this->imageURL = '/' . $this->path . '/' . $this->filename;

So I'd like to say:

$this->imageURL = '/' . $this->path -/wp-content/themes/tray/ . '/' . $this->filename;

PHP substr()? strpos()?


Solution

  • Given that:

    $this->imageURL = '/' . $this->path . '/' . $this->filename;
    $remove = "/wp-content/themes/tray";
    

    This is how to remove a known prefix, if it exists:

    if (strpos($this->imageURL, $remove) === 0) {
        $this->imageURL = substr($this->imageURL, strlen($remove));
    }
    

    If you are certain that it always exists then you can also lose the if condition.