Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing string for all matching patterns in php

I would like to match all the patterns like [[WHATEVER]]

The text inside those two brackets can be uppercase or lowercase, it can start with space or end with space and can be made of two or more words separated by space

$string = "The [[QUICK]] brown [[FOX]] jumped over [[whatever]]";

parse $string; //I would like an result to be like array

array( 0 => "[[QUICK]]", 1 => "[[FOX]]", 2 => "[[whatever]]") 

1 Answers

You can match them like this:

  $re = "/\\[{2}.*?\\]{2}/"; 
  $str = "The [[QUICK]] brown [[FOX]] jumped over [[whatever]]"; 
  preg_match_all($re, $str, $matches);
  print_r($matches[0]);

Output of a sample program:

Array                                                                                                                                                                                                                                                  
(                                                                                                                                                                                                                                                      
    [0] => [[QUICK]]                                                                                                                                                                                                                                   
    [1] => [[FOX]]                                                                                                                                                                                                                                     
    [2] => [[whatever]]                                                                                                                                                                                                                                
)    
like image 133
Wiktor Stribiżew Avatar answered Feb 05 '26 08:02

Wiktor Stribiżew