使用正则表达式返回数组中的子字符串

时间:2016-07-06 13:35:27

标签: php regex preg-match preg-match-all

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

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

返回:

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

我应该如何继续在PHP中返回?

2 个答案:

答案 0 :(得分: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]
)

答案 1 :(得分:1)

我假设所有这一切的最终目标是您要将[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?