Search code examples
phpregexpreg-replaceregex-groupsubstr

How to remove 2 last characters with preg_replace?


I have a code like : 784XX . XX could be a character or number and I need an expression to remove the last 2 characters (XX) using ( and only ) preg_replace.

How can I do that?

For example, the output of :

782A3 is 782,

0012122 is 00121,

76542A is 7654,

333333CD is 333333,

Solution

  • You can use substr function.

    But if you will use preg_replace you can do this:

    $val = preg_replace('/[\w\d]{2}$/', '', $val);