0

How can I add divider ; in the following variable which contains string

I have string like this:

$filename = "a.jpg3c.pngyes.jpg";

I would like to have something like

a.jpg;3c.png;yes.jpg

This string is created when I select multiple files to upload.

Is regex only solution in here?

user123_456
  • 5,011
  • 20
  • 80
  • 136
  • 4
    and how will you be able to tell that you've got 3 filenames in there, and not two files that are (say) "a.jpg.3c.png" and "yes.jpg"? or some other combo? "a.jpg3", 'c.png', 'yes', and '.jpg'? – Marc B Apr 23 '13 at 21:24
  • exactly...that is one of many problems in here...let me paste some more code – user123_456 Apr 23 '13 at 21:25
  • 1
    So your upload code concatenates all files into a single string without separators. Have you considered, well, not doing so in the first place? You can use a simple 3 element array. – Álvaro González Apr 23 '13 at 21:32
  • 1
    "This string is created when I select multiple files to upload." Well, stop doing it that way. Pass it as an array instead. – ceejayoz Apr 23 '13 at 21:34

2 Answers2

3

Regex is not the only solution! Perhaps you can use str_replace() instead of regex.

$filenames = "a.jpg3c.pngyes.jpg";

$img_extensions = array(".png", ".jpg", ".gif");
$semicolon_additions = array(".png;", ".jpg;", ".gif;");

$newfilenames = str_replace($img_extensions, $semicolon_additions, $filenames);

http://php.net/manual/en/function.str-replace.php

Edit: In your particular case, I would add in the semicolon at the end of the filename inside of your loop.

Chris Bier
  • 12,978
  • 15
  • 60
  • 100
1

Here is one option using regular expressions:

$filename = "a.jpg3c.pngyes.jpg";
$regex = '/\.(jpg|png|gif)(?!$)/';
$filename = preg_replace($regex, ".$1;", $filename);
Andrew Clark
  • 180,281
  • 26
  • 249
  • 286