簡體   English   中英

用php將內容添加到字符串上某個位置的最有效方法是什么

[英]What is the most efficient way to add content to a position on a string with php

我有一個字符串localhost/uploads/images/photo.jpg ,我只想簡單地將其重命名為localhost/upload/images/photo_thumb.jpg ,請記住這是一個動態數據,只是將其用於我想要的實現。 我嘗試使用strpos()函數獲取“。”的位置。 然后用它來做某事(這是我迷路的地方),然后我想到另一個使用爆裂的想法。 如果能幫助我解決這個問題,我將不勝感激。

<?php
function get_google_image_url($type, $id, $column = 'image', $multi = "",$thumb=''){
  if($multi ==''){
    //check if there is thumbnail add _thumb before extention
    if($thumb != ''){
      $l= $this->db->get_where($type,array($type.'_id'=>$id));
      $n = $l->num_rows();
      if($n >0){
        $value = $l->row()->$column;
        $position = strripos($value,'.');
        return $l->row()->$column;
      }
    }else{
      $l= $this->db->get_where($type,array($type.'_id'=>$id));
      $n = $l->num_rows();
      if($n >0){
        /$value = $l->row()->$column
          $position = strripos($value,'.');
        //this where i got stucked
        //return $l->row()->$column;
      }
    }
  }
}

那就是我要實現它的功能,但是我想要實現的就是我上面所說的。

我可以通過使用regex和preg_replace來做到這一點:

$string="localhost/uploads/images/photo_thumb.jpg";
$replacement="$1/$2_thumb.$3";
$pattern= '/([\w+\/]*)(?=\/)\/([\w]+(?<!_thumb))\.(\w+)/i';
echo preg_replace($pattern, $replacement, $string);

您可以在此處運行的代碼

$1 = matching until last /

$2 = name of the file

$3 = file extension

如有需要,隨時改善正則表達式模式。

我認為最好的方法是使用pathinfo

這樣的東西應該工作

$path_parts = pathinfo('localhost/uploads/images/photo.jpg');
$strNewName = $path_parts['dirname'].'/photo_thumb.jpg';
echo $strNewName;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM