php自然比较排序忽略(但不删除)非数字数据
基本上,我有一个目录,其中包含一堆文件名,我已将它们加载到数组中。文件名告诉我有关它们所代表的文本的一些信息(即序言、第一章、第二章),但在文件名中我还包含一个序列号以保持它们的顺序。所以'prollecture1.xml','prollecture2.xml','prollecture3.xml',. 。 。 “prollecture12.xml”、“chapteronelecture13.xml”、“chapteronelecture14.xml”。 。 。 'conclusionlecture18.xml' 等。
我想对其进行排序,以便数组按数字顺序列出它们。使用“自然比较排序”让我接近,但排序从文件名的第一个字符开始,因此“chapteronelecture13.xml”列在“prollecture1.xml”之前,因为“c”位于“p”之前。如果我从一开始就知道我想这样做,我会把数字放在第一位。但现在要更改所有文件名将是一项繁重的工作。
我的问题:有没有办法获得“自然字符串比较”以忽略文件名的第一部分并从“lecture##”开始?或者甚至更好,排序是否可以忽略(但不删除)所有非数字数据并仅根据文件名中嵌入的数字对数组进行排序?
感谢您的帮助。
Basically, I have a directory with a bunch of files names that I have loaded into an array. The file names tell me something about the text they represent (i.e. Prologue, chapterone, chaptertwo), but in the file name I also include a sequential number to keep them ordered. So 'prollecture1.xml', 'prollecture2.xml', 'prollecture3.xml', . . . 'prollecture12.xml', 'chapteronelecture13.xml', 'chapteronelecture14.xml'. . . 'conclusionlecture18.xml', etc.
I want to sort this so that the array lists them in numerical order. Using a "natural comparison sort" gets me close, but the sort begins with the first character of the file name, and thus 'chapteronelecture13.xml' is listed before 'prollecture1.xml' because 'c' comes before 'p'. If had known I wanted to do this from the beginning I would have put the numbers first. But to change all the file names now would be a lot of work.
My question: is there a way to the get the "natural string comparison" to ignore the first part of the file name and begin at "lecture##"? Or even better, can the sort ignore (but not remove) all non-numeric data and sort the array solely by the numbers embedded in the file name?
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为没有内置函数可以做到这一点,但是使用 usort 你可以实现这一点:
preg_replace< /code> 返回 $a 或 $b 的副本,其中删除了所有非数字字符(我尚未测试它,但我认为它有效)。
I think there's no built-in function that do this, but using usort you may accomplish that:
the
preg_replace
returns a copy of $a or $b with all non-numerical characters removed (I haven't tested it, but I think it works).您应该编写一个脚本来为您重命名所有文件。不要编写一些 hack 来克服文件的错误命名。这很可能会在未来引起更多的麻烦。
编写一个脚本来重命名文件应该不会太难,对于小于 10 的数字使用前导 0,对于小于 10 的数字使用两个前导零,对于 10 到 99 之间的数字使用一个前导零。
filename001.xml
filename002.xml
那么你的排序就会完美。
You should write a script that renames all of the files for you. Don't write some hack to overcome the wrong naming of the files. This will most liekly cause more headaches in the future.
Shoudln't be too hard to write a script that renames the files with a leading 0 for numbers less than 10, or even two leading zeros for numbers less than 10, and one leading zero for numbers between 10 and 99.
filename001.xml
filename002.xml
Then your sort will work perfect.