2012-06-28 17 views
8

mam ciągi:Pobierz numery z ciągiem w PHP

$one = 'foo bar 4 baz (5 qux quux)'; 
$two = 'bar baz 2 bar'; 
$three = 'qux bar 12 quux (3 foo)'; 
$four = 'foo baz 3 bar (13 quux foo)'; 

Jak mogę znaleźć Cyfry w tych ciągów?

Może z funkcji:

function numbers($string){ 

    // ??? 

    $first = ?; 
    $second = ?; 
} 

Na przykład:

function numbers($one){ 

    // ??? 

    $first = 4; 
    $second = 5; 
} 

function numbers($two){ 

    // ??? 

    $first = 2; 
    $second = NULL; 
} 

najlepszym sposobem na to może jest regex, ale jak mogę to wykorzystać na moim przykładzie? Może bez regex?

+0

Chcesz dopasować tylko cyfry? Nie można również konwertować 'one' na' 1'? – DaveRandom

+0

Twoje pytanie nie jest jasne, czy chcesz wyodrębnić tylko liczby z ciągu? – bodi0

+0

Wystarczy popatrzeć na to ... to będzie punkt, w kierunku ... http://stackoverflow.com/questions/1077600/converting-words-to-numbers-in-php – Brian

Odpowiedz

22

Można użyć regular expressions do tego. \descape sequence dopasuje wszystkie cyfry w temacie.

Na przykład:

<?php 

function get_numerics ($str) { 
    preg_match_all('/\d+/', $str, $matches); 
    return $matches[0]; 
} 

$one = 'foo bar 4 baz (5 qux quux)'; 
$two = 'bar baz 2 bar'; 
$three = 'qux bar 12 quux (3 foo)'; 
$four = 'foo baz 3 bar (13 quux foo)'; 

print_r(get_numerics($one)); 
print_r(get_numerics($two)); 
print_r(get_numerics($three)); 
print_r(get_numerics($four)); 

https://3v4l.org/DiDBL

6

można zrobić:

$str = 'string that contains numbers'; 
preg_match_all('!\d+!', $str, $matches); 
print_r($matches); 
5

Oto moja próba BEZ wyrażenie regularne

function getNumbers($str) { 
    $result = array(); 

    // Check each character. 
    for($i = 0, $len = strlen($str); $i < $len; $i++) { 
     if(is_numeric($str[$i])) { 
      $result[] = $str[$i]; 
     } 
    } 

    return $result; 
} 

$one = 'one two 4 three (5 four five)'; 
$two = 'one two 2 three'; 
$three = 'one two 12 three (3 four)'; 
$four = 'one two 3 three (13 four five)'; 

var_dump(getNumbers($one)); 
var_dump(getNumbers($two)); 
var_dump(getNumbers($three)); 
var_dump(getNumbers($four)); 

// output:

array(2) { 
    [0]=> 
    string(1) "4" 
    [1]=> 
    string(1) "5" 
} 

array(1) { 
    [0]=> 
    string(1) "2" 
} 

array(3) { 
    [0]=> 
    string(1) "1" 
    [1]=> 
    string(1) "2" 
    [2]=> 
    string(1) "3" 
} 

array(3) { 
    [0]=> 
    string(1) "3" 
    [1]=> 
    string(1) "1" 
    [2]=> 
    string(1) "3" 
} 
+1

'BEZ wyrażenia regularnego' - Godny pochwały, ale głupi na tę pracę. Regex będzie tu znacznie lepiej/szybciej - zwłaszcza, że ​​wywołujesz 'strlen()' w każdej iteracji raczej niż buforowanie w zmiennej wynik raz przed pętlą. Spróbuj tego z dużym ciągiem (a może nawet małym), a znajdziesz regex jest znacznie szybszy. – DaveRandom

+0

Zgadzam się, że to głupie, ale o to prosił OP :) – Greg

+0

to super sposób, człowiek thanx – Mevia