Check if a String Ends with a Number in PHP(检查字符串是否以 PHP 中的数字结尾)
问题描述
我正在尝试实现以下功能.最好在这里使用某种类型的正则表达式吗?我也需要获取号码.
I'm trying to implement the function below. Would it be best to use some type of regex here? I need to capture the number too.
function endsWithNumber($string) {
$endsWithNumber = false;
// Logic
return $endsWithNumber;
}
推荐答案
$test="abc123";
//$test="abc123n";
$r = preg_match_all("/.*?(d+)$/", $test, $matches);
//echo $r;
//print_r($matches);
if($r>0) {
echo $matches[count($matches)-1][0];
}
正则表达式解释如下:
.*?- 这将从一开始就占用字符串中的所有字符,直到也找到后续部分的匹配项.
.*? - this will take up all the characters in the string from the start up until a match for the subsequent part is also found.
(d+)$ - 直到字符串末尾的一位或多位数字,已分组.
(d+)$ - this is one or more digits up until the end of the string, grouped.
没有 ?在第一部分中,只有最后一个数字将在第二部分中匹配,因为它之前的所有数字都会被 .* 占用.*
without the ? in the first part, only the last digit will be matched in the second part because all digits before it would be taken up by the .*
这篇关于检查字符串是否以 PHP 中的数字结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查字符串是否以 PHP 中的数字结尾
基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01