检查字符串在PHP中是否以数字结尾

编程入门 行业动态 更新时间:2024-10-21 07:26:19
本文介绍了检查字符串在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]; }

正则表达式的解释如下:

the regex is explained as follows:

.*? -这将从开始就占据字符串中的所有字符,直到找到下一部分的匹配项为止.

.*? - 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中是否以数字结尾

本文发布于:2023-10-14 22:17:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492373.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   结尾   数字   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!