2017-10-06 22 views
1

j'ai besoin d'obtenir des chiffres à partir de chaînes comme ça:Trouver les numéros/positions spécifiques dans la chaîne

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

Dans un premier temps j'ai besoin peut-être sortir des lettres de chaîne:

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

... mais quelle est la prochaine?

Par exemple:

$string = 'main-section1-1'; 

Résultat attendu:

$str1 = 1; 
$str2 = 1; 

ou:

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

postez le résultat attendu – RomanPerekhrest

+0

« mais ce qui est la prochaine étape? » Tu nous as dit. Avez-vous essayé cela? Si oui, quel était le résultat attendu par rapport au résultat réel. –

Répondre

2

En utilisant 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] 
?> 

Sortie:

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

) 
1

Si je ne suis pas mal compris votre question cela fonctionnera pour vous 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