0
votes

I am using Twig templating for PHP with plugin (https://github.com/jasny/twig-extensions) that includes functions like preg_replace.

I have the follow strings:

Coverking_CSC_Neosupreme_1Row-F-150_Series-01-MASS 
Coverking_CSC_Neosupreme_1Row-F-150_Series-01-ANYTHING
Coverking_CSC_Neosupreme_1Row-F-150_Series-01

I want to replace the last occurrence of -XX or -XXANYTHING with empty string.

So the results of replacements for all strings above should be

Coverking_CSC_Neosupreme_1Row-F-150_Series

I managed to look online and found the following regular expression to remove the last occurrence of -XX

str|preg_replace("/\-[0-9]{2}(?!.*\-[0-9]{2})/","")

How can I modify the above regex to give me the desired results?

Thank you

2

2 Answers

1
votes

You can use this:

preg_replace("/-\d\d(-.*|)$/","","Coverking_CSC_Neosupreme_1Row-F-150_Series-01-MASS");
0
votes

If you want to strip anything from the -XX- up until the end, use the $ anchor character to define you want to match up until the last character of the string.

You can do something like this:

{{ str|preg_replace("/\-[0-9]{2}(\-[\w\-]+)?$/", "") }}

The \w matches 0-9 A-Z and a-z.

See regex in action:

https://regex101.com/r/aiKMDn/2

edit:

Updated regex to have anything after -XX as optional match up until the end of the string.