1

I have a dynamic strings that outputs,

test-only
test-only-1
test-only-12
sample-only-2
sample-test-55
etc...

I would like to ask, how can i remove -1,-12,-2, -55 dynamically using php?

Thanks!

iamnards
  • 217
  • 2
  • 7
  • 18

3 Answers3

4
preg_replace('/-[0-9]+$/', '', $string);
J. Bruni
  • 20,322
  • 12
  • 75
  • 92
0

This will work when all of the input is on the same line.

preg_replace('/([a-z\-]+)(-[0-9]+)/', '$1', $data);

With input on multiple lines it would be best to anchor to the end of the string

preg_replace('/^([a-z\-]+)(-[0-9]+)$/', '$1', $data);
Orangepill
  • 24,500
  • 3
  • 42
  • 63
0

You can use preg_replace to replace with a regex. $string in the example below would be the text you are trying to fix. This will replace - and /d+ will replace numeric characters.

$pattern = '/\-/d+$/i';
print preg_replace($pattern, '', $string);
DSlagle
  • 1,563
  • 12
  • 19