将字符串爆炸为由大写字母分隔的数组

时间:2014-04-15 03:24:27

标签: php arrays

我将从示例字符串

开始
LampsHeated MirrorsPower Mirror(s)Intermittent WipersVariable Speed Intermittent WipersPower Driver SeatCloth SeatsBucket SeatsDriver Adjustable LumbarPass-Through Rear SeatRear Bench SeatFloor MatsAdjustable Steering WheelSteering Wheel Audio ControlsTire Pressure MonitorPower Door LocksKeyless EntryRemote Trunk ReleaseSecurity SystemCD ChangerCD PlayerPremium Sound SystemAuxiliary Audio InputA/CRear DefrostAuxiliary Pwr OutletDriver Vanity MirrorPassenger Vanity MirrorDriver Illuminated Vanity MirrorPassenger Illuminated Visor MirrorFront Reading LampsPassenger Air Bag SensorFront Head Air BagRear Head Air BagChild Safety LocksEmergency Trunk Release

因为你可以看到字符串有一个没有被任何东西分隔的项目列表,但它们都以一个大写字母开头。

所以我一直在寻找一种方法将这个字符串转换成一个由大写字母分隔的数组,但是他们还需要确保它不仅仅是同一个列表中的第二个字,所以我们检查它是否在它之前有空格或者也不是。

e.g。 '乘客虚荣MirrorDriver发光虚荣镜'

将成为阵列('乘客虚荣镜','司机照亮的梳妆镜')

我似乎无法理解如何做到这一点。我相信一个正则表达式,对检查首都会有好处,但是甚至不知道如何做到这一点。 有关如何解决这个问题的任何想法吗?

2 个答案:

答案 0 :(得分:2)

$var = preg_split('/(?<=\S)(?=[A-Z])/', 'Passenger Vanity MirrorDriver Illuminated Vanity Mirror');
var_dump($var);
//array(2) {
//  [0] =>
//  string(23) "Passenger Vanity Mirror"
//  [1] =>
//  string(32) "Driver Illuminated Vanity Mirror"
//}

Regular expression visualization

Debuggex Demo

但我不知道如何处理缩写。

P.S。表达式/(?<=\S)(?<![\-A-Z\/])(?=[A-Z])/,用于处理样本数据。

答案 1 :(得分:2)

我能想到的最好但是我怀疑它会完美无缺地运作

preg_split('/(?<=[^A-Z\s\/-])(?=[A-Z])/', $str)

此表达式归结为“拆分任何大写字母前面的任何大写字母,不是大写字母,空格,正斜杠或连字符”

您也可以使用

preg_split('/(?<![A-Z\s\/-])(?=[A-Z])/', $str, -1, PREG_SPLIT_NO_EMPTY)

基本上是相同的东西,它只使用带有正面角色类的负面后视,而不是第一个例子中带有否定角色类的正面后卫。 PREG_SPLIT_NO_EMPTY删除空的第一个项目。

给我以下数组...

Array
(
    [0] => Lamps
    [1] => Heated Mirrors
    [2] => Power Mirror(s)
    [3] => Intermittent Wipers
    [4] => Variable Speed Intermittent Wipers
    [5] => Power Driver Seat
    [6] => Cloth Seats
    [7] => Bucket Seats
    [8] => Driver Adjustable Lumbar
    [9] => Pass-Through Rear Seat
    [10] => Rear Bench Seat
    [11] => Floor Mats
    [12] => Adjustable Steering Wheel
    [13] => Steering Wheel Audio Controls
    [14] => Tire Pressure Monitor
    [15] => Power Door Locks
    [16] => Keyless Entry
    [17] => Remote Trunk Release
    [18] => Security System
    [19] => CD Changer
    [20] => CD Player
    [21] => Premium Sound System
    [22] => Auxiliary Audio Input
    [23] => A/CRear Defrost
    [24] => Auxiliary Pwr Outlet
    [25] => Driver Vanity Mirror
    [26] => Passenger Vanity Mirror
    [27] => Driver Illuminated Vanity Mirror
    [28] => Passenger Illuminated Visor Mirror
    [29] => Front Reading Lamps
    [30] => Passenger Air Bag Sensor
    [31] => Front Head Air Bag
    [32] => Rear Head Air Bag
    [33] => Child Safety Locks
    [34] => Emergency Trunk Release
)

如您所见, A / C 后部除霜

存在问题