How to remove a specific part of a string

Asked

Viewed 2,452 times

3

Let’s say I have a file called Icon.png and I’ll zip it up, it’ll stay Icon.png.zip but I want you to call yourself just Icon.zip, how do I remove the part .png of the file name?

2 answers

5


If you use PHP 5.2.0 up, you can use the function pathinfo with the constant PATHINFO_FILENAME, this will return you only the file name. So, just concatenate the .zip:

<?php
  $nome_arquivo = "Icon.png";
  $novo_nome =  pathinfo($nome_arquivo, PATHINFO_FILENAME) . '.zip';
  echo $novo_nome; // Retorna "Icon.zip"
?>

Ideone: https://ideone.com/14vP36


For versions below, you need to use the constant PATHINFO_BASENAME, but this will return us the entire file name (using the first code as an example, Icon.png). What you can do is use the preg_replace to get the file name and then concatenate the .zip. Example:

<?php
  $nome_arquivo = "Icon.png";
  $arquivo = pathinfo($nome_arquivo, PATHINFO_BASENAME);
  $novo_nome = preg_replace('/(.+?)\.[^.]*$|$/', '$1', $nome_arquivo) . '.zip';
  echo $novo_nome; // Retorna "Icon.zip"
?>

Ideone: https://ideone.com/5F04Jr

1

You can use the function str_replace, see a functional example here.

<?php
    $valor = "Icon.png.zip";
    $valor = str_replace(".png", "", $valor);
    echo $valor;
?>

You can also pass an array containing the words you want to replace:

<?php
    // array com os valores que devem ser substuidos
    $ext = array(".png", ".jpg", ".gif");

    $png = "IconPNG.png.zip";
    $png = str_replace($ext, "", $png);

    $jpg = str_replace($ext, "", "IconJPG.jpg.zip");

    echo $png . "\n";
    echo $jpg;
?>

Functional example here.

  • Vlw for your help. however I won’t know what file extension to use replace :c

  • Got it! All right. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.