2016-07-06 10 views
-1

Ich habe die folgende Zeichenfolge, zB: 'Hello [owner], we could not contact by phone [phone], it is correct?'.Teilstring im Array mit Regex zurückgeben

Regex möchte in Form von Array zurückgeben, alles, was innerhalb [] ist. Innerhalb der Klammer werden nur Alpha-Zeichen.

Return:

$array = [ 
    0 => '[owner]', 
    1 => '[phone]' 
]; 

Wie sollte ich vorgehen, in php diese Rückkehr zu haben?

+1

Sie haben diese Frage mit 'preg-match-all' markiert - die Dokumentation dieser Funktion enthält nützliche Beispiele. Hast du es ausprobiert? – Jon

Antwort

1

Versuchen:

$text = 'Hello [owner], we could not contact by phone [phone], it is correct?'; 
preg_match_all("/\[[^\]]*\]/", $text, $matches); 
$result = $matches[0]; 
print_r($result); 

Ausgang:

Array 
(
    [0] => [owner] 
    [1] => [phone] 
) 
+0

Vielen Dank! Es funktionierte! – pedrosalpr

1

Ich gehe davon aus, dass das Endziel all dies ist, dass Sie die [placeholder] s mit einem anderen Text ersetzen wollen, so verwenden statt preg_replace_callback:

<?php 
$str = 'Hello [owner], we could not contact by phone [phone], it is correct?'; 

$fields = [ 
    'owner' => 'pedrosalpr', 
    'phone' => '5556667777' 
]; 

$str = preg_replace_callback('/\[([^\]]+)\]/', function($matches) use ($fields) { 
    if (isset($fields[$matches[1]])) {    
    return $fields[$matches[1]];      
    } 
    return $matches[0];    
}, $str);   

echo $str; 
?> 

Ausgang:

 
Hello pedrosalpr, we could not contact by phone 5556667777, it is correct?