2016-07-06 92 views
-1

我有以下字符串,例如:'Hello [owner], we could not contact by phone [phone], it is correct?'返回子串与正则表达式

正则表达式想返回数组的形式,所有这一切都在[]之内。括号内只有字母字符。

返回:

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

我应该如何着手有这个回报率在PHP?

+1

您已标记此问题'preg-match-all' - 该函数的文档具有有用的示例。你试过了吗? – Jon

回答

1

尝试:

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

输出:

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

谢谢!有效! – pedrosalpr

1

我假设这一切的最终目标是要与其它一些文本,以取代[placeholder] S,所以在使用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; 
?> 

输出:

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