1

Working with a ficticuous string such as;

$string = 'Ford : LTD 1988 Ford Station Wagon with HP 351 H Engine and Performance Transmission';

How could I use rexexp or preg_match (I don't know which would be better either) to extract a sequence of letters and numbers ("HP 351 H") from that string to use in another variable (ie: $EngineSize)

The above is a fictious example, I'm just trying to make it clear that I'm trying to extract letters and numbers from a UI.

NOTE: Being that this is coming from a UI, the engine size may be positioned anywhere in the string and the format may be with or without spaces and may or may not have a letter at the end, as well as the model could be 2 or 3 letters (ie; LE, LT, LTD etc) as well as the engine size could be 2 - 3 digits possibly followed by 2 or three letters).

If anyone wouldn't mind showing me how to write an expression to retrieve this data and explain to me which is better (regexp or preg_match) I'd be most appreciative and I thank you in advance.

4

1 回答 1

2

The following regex matches exactly what you describe, but there is a good chance of false positives:

/(?<=\s|^)[a-zA-Z]{2,3} ?\d\d\d? ?[a-zA-Z]{1,3}?(?=\s|$)/
于 2013-11-08T14:50:13.727 回答