2012-05-14 56 views
0
$str = "234 567 some text following"; 

如何从字符串中的第三个字符到最后一个数字得到一个子字符串?PHP子串到字符串中的最后一个数字

编辑
我的问题似乎并不清楚从给出的答案。在上面的例子中,我希望返回子字符4 567,而不是从第三个字符到字符串结尾。谢谢。

2nd编辑
这只是一个示例字符串...字符串可能是文本和数字的混合。我需要从已知位置到最后出现的数字的位置进行子串处理。

+0

使用正则表达式 - http://php.net/manual/en/function.preg-match.php – ChrisW

+1

你这是什么期望? '4 567'? – xdazz

+0

是的,4 567是我期望的 – Owen

回答

0

你应该使用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]/' 
+1

我不确定这是非常有用的 - 他想要最后一个**号**,而不是最后一个**字符** – ChrisW

+0

误读;)也许正则表达式在这种情况下? – jbduzan

+0

返回一个空数组。 – Owen

0

试试这个:

substr($str,2,strlen($str)); 

EDIT(新的答案):

此代码的工作:

$str = preg_replace("/\D/", "", $str); 
echo substr($str,2); 
+0

如果你想要最后一个字符,不需要strlen。 – jbduzan

+0

是啊,没错,我只是认为如果情况下问题还不清楚。ty –

+0

@jbduzan但他**并不希望它到最后一个字符!他希望它到最后**号** – ChrisW

0
<?php 
    $subStr = substr($str, 2); 
?> 

缺省情况下的长度(第三个参数)中,当离开了,将默认为字符串的末尾。请注意,字符从0开始,所以第三个字符将位于位置2.

0

您可以在正则表达式中使用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

0

我只是偶然发现了这一点,并认为我会分享我的解决方案。

<?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); 
相关问题