Skip to content
Advertisement

PHP regex to convert dimensions like N*N and NxN into N x N

I have a series of search terms entered by users, asking the same thing in different ways. For example someone is searching for frame 8 x 10 frame. They often search in the following ways:

8x10 frame
8*10 frame
8 * 10 frame
8 x 10 frame
8x10 photo frame

Stylistically, I prefer N x N, so I would prefer to convert all variations of NxN, N*N, N * N into N x N.

Examples:

8x10 frame -> 8 x 10 frame 8*10 frame -> 8 x 10 frame 8x10 photo frame -> 8 x 10 photo frame

I’ve tried using str_replace, but there are so many if-else conditions my code has become unmanageable. I feel like I’m not the first to have this issue, hoping some nice regex or build-in function exists.

EDIT: I used “8 x 10” as an example, but we need to consider any custom combinations like “4 x 3”, “12 x 4” and so on.

Advertisement

Answer

Using a regular expression, you can use…

echo preg_replace("/(d+)s*[Xx*]s*(d+)/", "$1 x $2", $a);

the pattern is

(d+) - Any number of digits
s* - 0 or more spaces
[Xx*] - either X, x or *
s* - 0 or more spaces
(d+) - Any number of digits

which gets replaced with "$1 x $2", so this gives the consistent output.

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