Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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, i.e. after the last space. Tried to adapt similar answers but no luck:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Is there an easy way to achieve this?

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading