Yamaha32088
Yamaha32088

Reputation: 4163

Comparing all but the last part of a string with PHP

I am working on a batch product upload excel file where the requirements are for each image other than the main image need to be separated by a pipe "|" character with no spaces. I have written a script to echo out all of the image names with the URL concatenated to the beginning of the image name. What I now need to do is compare the image names so that they are grouped accordingly. I have the array that contains the image URL's sorted from low to high. The naming convention is something along the lines of:

03511alt1.jpg
03511alt2.jpg
03511alt3.jpg
0411453alt1.jpg
0411453alt2.jpg

So on and so forth they all start with digits and end with a digit so I need to group them such that it reads

03511alt1.jpg|03511alt2.jpg|03511alt3.jpg
0411453alt1.jpg|0411453alt2.jpg

Is there a PHP function to do a comparison like this?

Upvotes: 0

Views: 37

Answers (1)

kelunik
kelunik

Reputation: 6908

You can extract the first part using an int cast if there are only digits:

$id = (int) $filename;

Note: This will remove any leading zeros.

Then you can group them in an array:

$imgs[$id][] = $filename

You can then concatenate your filenames:

foreach($imgs as $id => $items) {
    print implode("|", $items);
}

Upvotes: 1

Related Questions