1

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

4

3 回答 3

4

鉴于:

$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条件。

于 2012-04-10T23:35:20.770 回答
2

这是一种选择:

$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().

$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”等其他主题。请注意仅针对您的特定用例编写内容。总是试图弄清楚代码是如何破坏的,并围绕有问题的假设用例进行编程。

于 2012-04-10T23:36:56.507 回答
1

尝试这个 :

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

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

$this->imageURL = '/' . str_replace("/wp-content/themes/tray/","",$this->path) . '/' . $this->filename;
于 2012-04-10T23:33:45.537 回答