[英]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.