2017-10-06 141 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