Return 正则表达式数组中的子字符串

Return substring in array with regex

我有以下字符串,例如:'Hello [owner], we could not contact by phone [phone], it is correct?'.

正则表达式想以return的形式数组化,全部在[]之内。括号内只有字母字符。

Return:

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

我应该如何在 php 中获得此 return?

尝试:

$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]
)

我假设所有这一切的最终目标是您想用其他文本替换 [placeholder],因此请改用 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?