如何检查字符串是否以数字结尾,如果为true,则将数字推送到数组中(例如)?我知道如何检查字符串是否以数字结尾,我这样解决了它:
$mystring = "t123";
$ret = preg_match("/t[0-9+]/", $mystring);
if ($ret == true)
{
echo "preg_match <br>";
//Now get the number
}
else
{
echo "no match <br>";
}
让我们假设所有字符串都以字母t
开头,并与一个数字合成,例如t1
、t224
、t353253
。。。
但是,如果有这个数字,我该怎么删掉呢?在我的代码示例中,字符串末尾有123
,我如何将其剪切出来,例如将其推送到具有array_push
的数组中?
$number = preg_replace("/^t('d+)$/", "$1", $mystring);
if (is_numeric($number)) {
//push
}
这应该会给你最后的数字。只需检查是否为数字,将其推送到您的阵列
样品:https://3v4l.org/lYk99
编辑:
只要意识到这对像t123t225
这样的字符串不起作用。如果您需要支持这种情况,请使用以下模式:/^t.*?('d+)$/
。这意味着它试图捕获以数字结尾的内容,忽略t
和数字之间的所有内容,并且必须从t
开始。
样品:https://3v4l.org/tJgYu
首先,您的正则表达式有点错误(可能是拼写错误),但要回答您的问题,您可以使用lookbacking和匹配数组,如下所示:
$test = 't12345';
if(preg_match('/(?<=t)('d+)/', $test, $matches)){
$result = $matches[0];
echo($result);
}
您应该使用preg_match中的第三个参数来获取匹配项,并且应该有数字,然后像这样更改正则表达式:([0-9]+)
所以代码应该是这样的:
$mystring = "t123";
$ret = preg_match("/([0-9]+)/", $mystring, $matches);
if ($ret == true)
{
print_r($matches); //here you will have an array of matches. get last one if you want last number from array.
echo "prag_match <br>";
}
else
{
echo "no match <br>";
}
在preg_match
函数中再添加一个参数,我想建议使用其他正则表达式来从任何字符串的最后一个中获取数字。
$array = array();
$mystring = "t123";
$ret = preg_match("#('d+)$#", $mystring, $matches);
array_push($array, $matches[0]);
$mystring = "t58658";
$ret = preg_match("#('d+)$#", $mystring, $matches);
array_push($array, $matches[0]);
$mystring = "this is test string 85";
$ret = preg_match("#('d+)$#", $mystring, $matches);
array_push($array, $matches[0]);
print_r($array);
输出
Array
(
[0] => 123
[1] => 58658
[2] => 85
)