使用 preg_match() 或其他 preg func 从字符串中获取连字符后的数字
Using preg_match() or other preg func to get number after hyphen from a string
我喜欢这样的员工守则
EMP-0006
如何获取连字符后的数字?
喜欢0006
或者即使是整数值那么6
我的意思是如果有某种方式 EMP343-0006
,那么我不想要连字符前的数字 -
只有连字符后的数字?
我不擅长 preg,所以我尝试研究是否已经有人问过它之类的,有很多正则表达式问题,但 none 是我想要的。
e-g
<?php
$string = "EMP2-0002";
echo preg_replace("/[^0-9]/","",$string);
现在如果我们看到它 return 所有数字,如何将它调整为 return 只有连字符后的数字?或者还有其他更好的解决方案吗?学习正则表达式似乎没什么难度。
如果你想用 preg_replace
:
echo preg_replace('/^.*-([0-9]+)$/', '', $string);
编辑:您也可以使用 explode
:
$parts = explode('-', $string);
echo $parts[1];
您可以尝试将 -\d+
作为正则表达式。我推荐像 https://regex101.com/ 这样的图形正则表达式编辑器来创建表达式。查看表达式作用的(图形)描述要容易得多。
编辑:您可以使用群组:
$matches = null;
$returnValue = preg_match('/-(?<number>\d+)/', 'EMP-0006', $matches);
您将通过访问$matches["number"]
获得号码。那么你就不必替换部分字符串了。
我喜欢这样的员工守则
EMP-0006
如何获取连字符后的数字?
喜欢0006
或者即使是整数值那么6
我的意思是如果有某种方式 EMP343-0006
,那么我不想要连字符前的数字 -
只有连字符后的数字?
我不擅长 preg,所以我尝试研究是否已经有人问过它之类的,有很多正则表达式问题,但 none 是我想要的。
e-g
<?php
$string = "EMP2-0002";
echo preg_replace("/[^0-9]/","",$string);
现在如果我们看到它 return 所有数字,如何将它调整为 return 只有连字符后的数字?或者还有其他更好的解决方案吗?学习正则表达式似乎没什么难度。
如果你想用 preg_replace
:
echo preg_replace('/^.*-([0-9]+)$/', '', $string);
编辑:您也可以使用 explode
:
$parts = explode('-', $string);
echo $parts[1];
您可以尝试将 -\d+
作为正则表达式。我推荐像 https://regex101.com/ 这样的图形正则表达式编辑器来创建表达式。查看表达式作用的(图形)描述要容易得多。
编辑:您可以使用群组:
$matches = null;
$returnValue = preg_match('/-(?<number>\d+)/', 'EMP-0006', $matches);
您将通过访问$matches["number"]
获得号码。那么你就不必替换部分字符串了。