2017-10-06 134 views
1

我需要从字符串得到的数字一样,具体的数字/职务:查找字符串

main-section1-1 
... 
main-section1-512 
... 
main-section10-12 

起初也许我需要从字符串走出字母:

preg_replace("/[^0-9-]+/i", "", $string); 

...但接下来呢?

例如:

$string = 'main-section1-1'; 

预期结果:

$str1 = 1; 
$str2 = 1; 

或:

$str = array(1,1); 
+0

发布预期的结果 – RomanPerekhrest

+0

“但接下来会发生什么?”你告诉我们。你尝试过吗?如果是这样,预期结果与实际结果是什么。 –

回答

2

使用preg_match_all()

<?php 
$string = "main-section1-1"; 
preg_match_all("/[0-9]+/", $string, $match); 
print_r($match); 

// for main-section1-512, you will get 1 and 512 in $match[0] 
?> 

输出:

[[email protected] tmp]$ php test.php 
Array 
(
    [0] => Array 
     (
      [0] => 1 
      [1] => 1 
     ) 

) 
1

如果我没有误解你的问题,这会为你工作https://eval.in/875419

$re = '/([a-z\-]+)(\d+\-\d+)/'; 
$str = 'main-section1-512'; 
$subst = '$2'; 

$result = preg_replace($re, $subst, $str); 
list($str1,$str2) = explode('-',$result); 
echo $str1; 
echo "\n"; 
echo $str2