0

I have some of this text value like

$str = 'A quick [color] [animal] [action] over the lazy dog.';

I want to find all the data with this "[" and "]" so if I have a long text ill just do [phone_number] or something. Can I achieve this into an array value?

My wanted output:

$array = ('[color]','[animal]','[action]');

cause I will use this later on for str_replace(). Is there anyway to do this?

Thank you for your help

jww
  • 97,681
  • 90
  • 411
  • 885

1 Answers1

2

You want to use preg_match_all:

$str = "A quick [color] [animal] [action] over the lazy dog.";
preg_match_all("/\[[^\]]*\]/", $str, $matches);
echo json_encode($matches); // [["[color]","[animal]","[action]"]]
caitlin
  • 2,769
  • 4
  • 29
  • 65