简体   繁体   中英

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() ?

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.

This is one option:

$h="/wp-content/themes/tray/img/celebrity_photos/photo-on-4-6-12-at-3-23-pm.jpg";

$prefix="/wp-content/themes/tray/";

print str_replace($prefix, "/", $h, 1);

It suffers from one major flaw, which is that it doesn't anchor itself to the left-hand-side of $h . To do this, you'd either need to use a regular expression (which is heavier on processing) or wrap this in something that detects the position of your prefix before running the str_replace() .

$h="/wp-content/themes/tray/img/celebrity_photos/photo-on-4-6-12-at-3-23-pm.jpg";

$prefix="/wp-content/themes/tray/";

if (strpos(" ".$h, $prefix) == 1)
  $result = str_replace($prefix, "/", $h, 1);
else
  $result = $h;

print $result;

Note this important element: the prefix ends in a slash. You don't want to match other themes like "trayn" or "traypse". Beware writing things for just your specific use case. Always try to figure out how code might break, and program around problematic hypothetical use cases.

Try this:

$href = str_replace("/wp-content/themes/tray","",$href);

Or in your specific case, something like this:

$this->imageURL = '/' . str_replace("/wp-content/themes/tray/","",$this->path) . '/' . $this->filename;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM