Skip to content
Advertisement

How to parse a mostly consistent filename into meaningful parts?

I have filenames like:

JavaScript

Luckily, the file naming is pretty consistent, but I can’t absolutely guarantee that someone didn’t use a space where they should have used an underscore.

With this in mind, I want to parse the string and extract the following details:

JavaScript

Presently, I use the following to grab this info:

JavaScript

$title is simply everything that’s left over after removing $parts[0] $parts[1], $parts[2], and end($parts), but how should I express that?

I thought I might be able to use

JavaScript

But this doesn’t remove the $revision bit at the end…

JavaScript

What am I missing, and am I unnecessarily over-complicating this?

Advertisement

Answer

The array_diff_key looks at key comparison of both arrays. end() just moves the internal pointer of the array and is actually useless since the value returned from it can’t be used in computing difference between 2 arrays’ keys.

Current comparison behaves as

JavaScript

which looks key wise as:

JavaScript

Hence, the end result of implode is concatenation of 4,5,6,7 keys’ values.

To make the second parameter array values as keys, you can use array_flip to make keys as values and values as keys with the below expression:

JavaScript

Demo: https://3v4l.org/J6b5r

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement