Example of PHP Regular Parsing Multiple Loop Templates

  • 2021-10-24 19:01:11
  • OfStack

In this paper, an example is given to describe the PHP regular parsing multiple loop template. Share it for your reference, as follows:


$str = " Hello customer, I recommend the following items for you: (crm{ Project 2: Project name } (crm{ Project 3: Project name }crm)  crm) As well as (crm{ Project 1: Project name }crm)";
$start = '(crm'; // Loop start tag 
$end  = 'crm)'; // Loop end tag    
// Loop mark, the symbol that needs to be transferred, and the escape character needs to be added in front of it  '\'
$need_escape = array('^', '$', '(', ')', '.', '[', ']', '|', '*', '?', '+', '/', '{', '}');
foreach($need_escape as $val)
{
   if(strpos($start, $val) !== FALSE)// There are symbols that need to be escaped 
   { 
     $escape = '\\'.$val;
     $start = str_replace($val, $escape, $start);
   }
   if(strpos($end, $val) !== FALSE)// There are symbols that need to be escaped 
   { 
     $escape = '\\'.$val;
     $end = str_replace($val, $escape, $end);
   }
}
/*----------------------------------
*  Regular analysis of "loop" without "sub-loop" 
*  "No sub-loop" : Does not contain loop start tag 
*  "Loop": Included by the loop tag ( Start tag, end tag )
* ---------------------------------*/
//$pattern = '/\(crm((?!\(crm).)+crm\)/U';
$pattern = '/'.$start.'((?!'.$start.').)+'.$end.'/U';
preg_match_all($pattern, $str, $matches);
echo "<pre>";
print_r($matches);
echo "</pre>";

Run results:

Array
(
[0] = > Array
(
[0] = > (crm {Project 3: Project Name} crm)
[1] = > (crm {Project 1: Project Name} crm)
)
[1] = > Array
(
[0] = > }
[1] = > }
)
)

PS: Here are two very convenient regular expression tools for your reference:

JavaScript Regular Expression Online Test Tool:
http://tools.ofstack.com/regex/javascript

Regular expression online generation tool:
http://tools.ofstack.com/regex/create_reg

For more readers interested in PHP related content, please check the topics on this site: "Summary of php Regular Expression Usage", "php Programming Security Tutorial", "Summary of php Security Filtering Skills", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of php String (string) Usage" and "Introduction to php+mysql Database Operation"

I hope this article is helpful to everyone's PHP programming.


Related articles: