2012-11-30 9 views
7

ho una stringa che ha hash tag in esso e sto cercando di tirare i tag fuori Credo di essere abbastanza vicino, ma ottenere un array multi-dimensionale, con gli stessi risultatiCome posso estrarre parole che iniziano con un tag cancelletto (#) da una stringa in un array

$string = "this is #a string with #some sweet #hash tags"; 

    preg_match_all('/(?!\b)(#\w+\b)/',$string,$matches); 

    print_r($matches); 

da cui si ricava

Array ( 
    [0] => Array ( 
     [0] => "#a" 
     [1] => "#some" 
     [2] => "#hash" 
    ) 
    [1] => Array ( 
     [0] => "#a" 
     [1] => "#some" 
     [2] => "#hash" 
    ) 
) 

voglio solo un array con ogni parola che inizia con un tag hash.

risposta

14

questo può essere fatto dal /(?<!\w)#\w+/ regx funzionerà

+0

vi ringrazio molto. ha funzionato !! – Nikz

+1

@Nikz siete i benvenuti ... :) felice di aiutare –

+0

come estrarre tutti i mondi con una parola chiave iniziale? –

3

Questo è quello che fa preg_match_all. Ottieni sempre un array multidimensionale. [0] corrisponde alla corrispondenza completa e [1] alla prima lista di risultati dei gruppi di acquisizione.

Basta accedere a $matches[1] per le stringhe desiderate. (Il tuo discarica con il raffigurato estranea Array ([0] => Array ([0] non era corretto È possibile ottenere un livello sottoarray..)

2

penso che questa funzione vi aiuterà a:

echo get_hashtags($string); 

function get_hashtags($string, $str = 1) { 
    preg_match_all('/#(\w+)/',$string,$matches); 
    $i = 0; 
    if ($str) { 
     foreach ($matches[1] as $match) { 
      $count = count($matches[1]); 
      $keywords .= "$match"; 
      $i++; 
      if ($count > $i) $keywords .= ", "; 
     } 
    } else { 
     foreach ($matches[1] as $match) { 
      $keyword[] = $match; 
     } 
     $keywords = $keyword; 
    } 
    return $keywords; 
} 
0

Prova:

$string = "this is #a string with #some sweet #hash tags"; 
preg_match_all('/(?<!\w)#\S+/', $string, $matches); 
print_r($matches[0]); 
echo("<br><br>"); 

// Output: Array ([0] => #a [1] => #some [2] => #hash)