删除除带破折号的最后一个变量之外的所有字符和数字
Removing all characters and numbers except last variable with dash symbol
您好,我想在 php 中使用 preg_replace 删除一个字符,所以我这里有这段代码,我想删除除最后一位数字之外的所有字符、字母和数字有破折号 (-) 符号后跟数字所以这是我的代码。
echo preg_replace('/(.+)(?=-[0-9])|(.+)/','','asdf1245-10');
我预计结果会是
-10
上面的问题不是很好用。我检查了使用 http://www.regextester.com/ it seems like it works, but on the other side http://www.phpliveregex.com/ 的模式根本不起作用。我不知道为什么,但有人可以帮助解决这个问题吗?
非常感谢
我的第一个想法是在这种情况下使用 explode.. 像下面的代码一样简单。
$string = 'asdf1245-10';
$array = explode('-', $string);
end($array);
$key = key($array);
$result = '-' . $array[$key];
$result => '-10';
这里有一个方法:
echo preg_replace('/^.+?(-[0-9]+)?$/','','asdf1245-10');
输出:
-10
和
echo preg_replace('/^.+?(-[0-9]+)?$/','','asdf124510');
输出:
<nothing>
另一种方式:
$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+)/','', 'asdf1245-10');
您好,我想在 php 中使用 preg_replace 删除一个字符,所以我这里有这段代码,我想删除除最后一位数字之外的所有字符、字母和数字有破折号 (-) 符号后跟数字所以这是我的代码。
echo preg_replace('/(.+)(?=-[0-9])|(.+)/','','asdf1245-10');
我预计结果会是
-10
上面的问题不是很好用。我检查了使用 http://www.regextester.com/ it seems like it works, but on the other side http://www.phpliveregex.com/ 的模式根本不起作用。我不知道为什么,但有人可以帮助解决这个问题吗?
非常感谢
我的第一个想法是在这种情况下使用 explode.. 像下面的代码一样简单。
$string = 'asdf1245-10';
$array = explode('-', $string);
end($array);
$key = key($array);
$result = '-' . $array[$key];
$result => '-10';
这里有一个方法:
echo preg_replace('/^.+?(-[0-9]+)?$/','','asdf1245-10');
输出:
-10
和
echo preg_replace('/^.+?(-[0-9]+)?$/','','asdf124510');
输出:
<nothing>
另一种方式:
$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+)/','', 'asdf1245-10');