How to parse a string for a specific delimited section in PHP?

I have a line, for example, "[{XYZ123}] This is a test" and I need to parse the contents between [{and}] and drop it to another line. I suppose that to achieve this you need a regular expression, but since it is not for the faint of heart, I did not try and did not need your help.

What is the best way to output a fragment between [{and}]? Thanks in advance for your help!

+3
source share
3 answers
<?php
$str = "[{XYZ123}] This is a test";

if(preg_match('/\[{(.*?)}\]/',$str,$matches)) {

 $dump = $matches[1];

 print "$dump";  // prints XYZ123
}

?>
+4
source
$str = "[{XYZ123}] This is a test";
$s = explode("}]",$str);
foreach ($s as $k){
  if ( strpos($k,"[{") !==FALSE ){
    $t = explode("[{",$k); #or use a combi of strpos and substr()
    print $t[1];
  }
}
+3
source

The regex will be (?=\[\{).*(?=\}\]), although I don't know if php support is supported.

+2
source

Source: https://habr.com/ru/post/1734365/


All Articles