简体   繁体   中英

Smarty substring after last occurrence?

Need to get the style number out of text string:

'The style number is A456RT' 'Style A456RT' 'Style number is A456RT'

Need to get the A456RT part only, ie after the last space. Tried to adapt similar answers but no luck:

{$product.name|regex_replace:"/^\d+ /":""}

Is there an easy way to achieve this?

You can use

{$product.name|regex_replace:'/.*\s(\w+)$/':'$1'}

See the regex demo .

If the codes are not just alphanumeric, then you can use

{$product.name|regex_replace:'/.*\s(\S+)$/':'$1'}

and if there can be any trailing spaces:

{$product.name|regex_replace:'/.*\s(\S+)\s*$/':'$1'}

Details :

  • .* - any zero or more chars other than line break chars (if there can be line breaks, add s after the second / ) as many as possible
  • \s - a whitespace
  • (\S+) - Group 1: any one or more non-whitespace chars ( \w+ matches one or more letters, digits or underscores)
  • \s* - zero or more whitespaces
  • $ - end of string.

How about the much simpler:

/[^ ]+$/gm

That is...

[^ ] any character other than a space
+ One or more times
$ at the end of the line

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