删除除最后一个带有破折号的变量以外的所有字符和数字


Removing all characters and numbers except last variable with dash symbol

嗨,我想在php中使用preg_replace删除一个字符,所以我在这里有这个代码,我想删除整个字符,字母和数字,除了最后一个数字(s),其中有破折号(-)符号后面跟着一个数字,所以这是我的代码。

echo preg_replace('/(.+)(?=-[0-9])|(.+)/','','asdf1245-10');

我期望结果是

-10

上面的问题不是很好地工作。我使用http://www.regextester.com/检查了模式,似乎它有效,但另一方面http://www.phpliveregex.com/根本不起作用。我不知道为什么,但谁能帮我弄明白?

Thanks to lot

这样做:

echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf1245-10');
输出:

-10

echo preg_replace('/^.+?(-[0-9]+)?$/','$1','asdf124510');
输出:

<nothing>

我的第一个想法是使用爆炸在这种情况下。让它像下面的代码一样简单:

$string = 'asdf1245-10';
$array = explode('-', $string);
end($array);
$key = key($array);
$result = '-' . $array[$key];

$result => '-10';

换句话说:

$result = preg_match('~'A.*'K-'d+'z~', $str, $m) ? $m[0] : '';

模式细节:

'A     # start of the string anchor
.*     # zero or more characters
'K     # discard all on the left from match result
-'d+   # the dash and the digits
'z     # end of the string anchor

echo preg_replace('/('w+)(-'w+)/','$2', 'asdf1245-10');