繁体   English   中英

如何删除 url 的一部分?

[英]How to remove part of a url?

试图改变这个:

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

进入:

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

所以我只是想从 url 中删除/wp-content/themes/tray/

这是插件的 PHP 代码,它为每个锚路径构建一个变量:

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

所以我想说:

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

PHP substr() strpos()

鉴于:

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

这是删除已知前缀(如果存在)的方法:

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

如果您确定它始终存在,那么您也可以失去if条件。

这是一个选项:

$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);

它有一个主要缺陷,即它不会将自己锚定到$h的左侧。 为此,您需要使用正则表达式(这在处理上更重)或将其包装在运行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;

请注意这个重要元素:前缀以斜杠结尾 您不想匹配其他主题,例如“trayn”或“traypse”。 谨防只为您的特定用例编写内容。 始终尝试弄清楚代码可能会如何崩溃,并围绕有问题的假设用例进行编程。

试试这个:

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

或者在您的特定情况下,是这样的:

$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