Home > Net >  Smarty substring after last occurrence?
Smarty substring after last occurrence?

Time:02-10

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, i.e. 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?

CodePudding user response:

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.

CodePudding user response:

How about the much simpler:

/[^ ] $/gm

That is...

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