我有以下字符串,例如:'Hello [owner], we could not contact by phone [phone], it is correct?'
。返回子串與正則表達式
正則表達式想返回數組的形式,所有這一切都在[]
之內。括號內只有字母字符。
返回:
$array = [
0 => '[owner]',
1 => '[phone]'
];
我應該如何着手有這個回報率在PHP?
我有以下字符串,例如:'Hello [owner], we could not contact by phone [phone], it is correct?'
。返回子串與正則表達式
正則表達式想返回數組的形式,所有這一切都在[]
之內。括號內只有字母字符。
返回:
$array = [
0 => '[owner]',
1 => '[phone]'
];
我應該如何着手有這個回報率在PHP?
嘗試:
$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]
)
謝謝!有效! – pedrosalpr
我假設這一切的最終目標是要與其它一些文本,以取代[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?
您已標記此問題'preg-match-all' - 該函數的文檔具有有用的示例。你試過了嗎? – Jon