Search code examples
phpregexpreg-matchpreg-match-all

Return substring in array with regex


I have the following string, eg: 'Hello [owner], we could not contact by phone [phone], it is correct?'.

Regex would like to return in the form of array, all that is within []. Inside the bracket will only alpha characters.

Return:

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

How should I proceed to have this return in php?


Solution

  • Try:

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

    Output:

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