1

I need a preg_replace() expression that removes all characters (letters & punctuations) except numbers and css units. But i need it to match the exact units not letters in it.

For example I wrote this expression:

$check = preg_replace( '/[^(0-9|px|em|\%|pt|cm|auto)$]/', '', '80sd0sdfdfpx');
echo $check;

And the result is:

800px

Thats ok untill this example:

$check = preg_replace( '/[^(0-9|px|em|\%|pt|cm|auto)$]/', '', '5sdfasdfp');
echo $check;

And this returns:

5ap

As you can see it also returns the letters which css unit variables contains. Like a in auto and p in px.

So I need it to return the css units if the words exactly matches like in the first example.

Any help will be appreciated.

Eren Süleymanoğlu
  • 1,204
  • 3
  • 18
  • 26

1 Answers1

1

You may match and skip sequences you have and remove anything else using SKIP-FAIL regex:

$check = preg_replace( '/(?:[0-9%]|p[xt]|[ec]m|auto)(*SKIP)(*F)|./', '', '5sdfasdfp');
echo $check;

See PHP demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563