代码之家  ›  专栏  ›  技术社区  ›  Alcantara

使用php将内容添加到字符串位置的最有效方法是什么

  •  1
  • Alcantara  · 技术社区  · 6 年前

    我有一根绳子 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;
          }
        }
      }
    }
    

    这就是我试图实现的功能,但我想要实现的是我上面所说的。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Atural    6 年前

    我认为最好的方法是 pathinfo

    这样应该行得通

    $path_parts = pathinfo('localhost/uploads/images/photo.jpg');
    $strNewName = $path_parts['dirname'].'/photo_thumb.jpg';
    echo $strNewName;
    
        2
  •  0
  •   Edwin    6 年前

    我会使用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);
    

    代码您可以运行它 here

    $1 = matching until last /

    $2 = name of the file

    $3 = file extension

    如果需要,可以随意改进regex模式。