简体   繁体   中英

Finding position of last digit in string

I'm trying to format some number plates - I need to find the last digit in a string and add a space after it, eg

T4MAX  = T4 MAX
T53TES = T53 TES

I'm assuming I'll have to use preg_replace - I've tried the below to find the position in the string of the last digit, but it returns an empty array.

preg_match('/(0-9])/', $plate, $matches, PREG_OFFSET_CAPTURE);

Any ideas?

That's easy:

$str = 'T4MAX';

$str_with_space = preg_replace('~\d(?=\D*$)~', '$0 ', $str);

Online demo: http://ideone.com/Mqqqsh

Regex explanation:

~\\d(?=\\D*$)~ expression means - any digit \\d followed by anything that is not a digit \\D by the end of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM