简体   繁体   English

如何删除 url 的一部分?

[英]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.所以我只是想从 url 中删除/wp-content/themes/tray/

Here's the plug in's PHP code that builds a variable for each anchor path:这是插件的 PHP 代码,它为每个锚路径构建一个变量:

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

So I'd like to say:所以我想说:

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

PHP substr() ? PHP substr() strpos() ? 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.如果您确定它始终存在,那么您也可以失去if条件。

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 .它有一个主要缺陷,即它不会将自己锚定到$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() .为此,您需要使用正则表达式(这在处理上更重)或将其包装在运行str_replace()之前检测前缀的 position 的内容中。

$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".您不想匹配其他主题,例如“trayn”或“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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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