如何使用PHP删除动态内容中的字符串? [重复]

问题描述:

This question already has an answer here:

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!

</div>

此问题已经存在 这里有一个答案: p>

  • 如何从字符串中删除所有数字? 5 answers span > li> ul> div>

    我有一个输出的动态字符串, p>

     测试仅\ NTEST-仅-1 \ NTEST-仅-12 \ NSample个-仅-2 \ NSample个测试-55 \ NETC ... 
     代码>  PRE> 
     
      

    我想问一下,如何使用php动态删除-1,-12,-2,-55? p>

    谢谢! p> div>

preg_replace('/-[0-9]+$/', '', $string);

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);

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);