$str = "234 567 some text following";
如何从字符串中的第三个字符到最后一个数字得到一个子字符串?PHP子串到字符串中的最后一个数字
编辑
我的问题似乎并不清楚从给出的答案。在上面的例子中,我希望返回子字符4 567
,而不是从第三个字符到字符串结尾。谢谢。
2nd编辑
这只是一个示例字符串...字符串可能是文本和数字的混合。我需要从已知位置到最后出现的数字的位置进行子串处理。
$str = "234 567 some text following";
如何从字符串中的第三个字符到最后一个数字得到一个子字符串?PHP子串到字符串中的最后一个数字
编辑
我的问题似乎并不清楚从给出的答案。在上面的例子中,我希望返回子字符4 567
,而不是从第三个字符到字符串结尾。谢谢。
2nd编辑
这只是一个示例字符串...字符串可能是文本和数字的混合。我需要从已知位置到最后出现的数字的位置进行子串处理。
你应该使用SUBSTR功能
substr($str, 2);
编辑:
用正则表达式
$pattern = '/^[0-9]+/';
preg_match($pattern, substr($str, 2), $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
EDIT2: 测试,它的工作
$pattern = '/^([0-9][ ]*)+/';
preg_match($pattern, substr($str, 2), $matches);
print_r($matches);
EDIT3: 没看到你最后的编辑,建立一个新的^^
EDIT4:
$str = "234 567 some text 123 22 following 12 something";
$pattern = '/^([ ]*([0-9][ ]*)*([a-zA-Z][ ]*)*[0-9]*)*[0-9]/';
preg_match($pattern, substr($str, 2), $matches);
echo $matches[0];
给我4 567 some text 123 22 following 12
是什么找你期待?
编辑5:
新再次^^
'/^([0-9 :._\-]*[a-zA-Z]*[:._\-]*)*[0-9]/'
<?php
$subStr = substr($str, 2);
?>
缺省情况下的长度(第三个参数)中,当离开了,将默认为字符串的末尾。请注意,字符从0开始,所以第三个字符将位于位置2.
您可以在正则表达式中使用negative lookahead来完成此操作。
<?php
$lastNumber = getLastNumber("234 567 some text following");
var_dump($lastNumber);
function getLastNumber($string) {
preg_match("/[0-9](?!.*[0-9])/", $string, $match);
if (!empty($match[0])) return $match[0];
return false;
}
?>
编辑:对不起,我误读;以为你想要最后一个独立号码。
双编辑:这似乎是你想
<?php
$string = substr("234 567 some text 123 22 following", 2);
preg_match("/[0-9 ]+/", $string, $matches);
if (!empty($matches)) {
$number = intval(str_replace(" ", "", $matches[0]));
var_dump($number);
}
?>
什么作为它返回 “4567”。当然,你想留空间,只需使用$matches[0]
而不是$number
。
我只是偶然发现了这一点,并认为我会分享我的解决方案。
<?php
$string = "234 567 some text following";
$start = 2;
if(preg_match_all('/\d+/', $string, $sub)){
$lastNumber = end($sub[0]);
$newString = substr($string,$start, strrpos($string, $lastNumber) + strlen($lastNumber) - $start);
}
echo $newString;
此行获取所有的数字串中
if(preg_match_all('/\d+/', $string, $sub))
在这里,我们获取的最后一个号码
$lastNumber = end($sub[0]);
随后,我们发现数量最后一次出现,在使用strrpos
最后一个数字出现超过一次。然后,使用该位置的子提取从起始位置到最后一个号码:
$newString = substr($string,$start, strrpos($string, $lastNumber)
+ strlen($lastNumber) - $start);
使用正则表达式 - http://php.net/manual/en/function.preg-match.php – ChrisW
你这是什么期望? '4 567'? – xdazz
是的,4 567是我期望的 – Owen