tags:

views:

41

answers:

3

Hi folks,

I have a string, for example "[{XYZ123}] This is a test" and need to parse out the content in between the [{ and }] and dump into another string. I assume a regular expression is in order to accomplish this but as it's not for the faint of heart, I did not attempt and need your assistance.

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

+2  A: 

The regex would be (?=\[\{).*(?=\}\]), though I don't know if php supports look aheads.

David Kanarek
If php doesn't support look aheads, you can do it without lookaheads `\[\{(.*?)\]\}`
Amarghosh
True, I just don't know enough about php to tell him how to extract the backreference.
David Kanarek
I'm no good at php either, but if I remember correctly, `$1` syntax works in php.
Amarghosh
+4  A: 
<?php
$str = "[{XYZ123}] This is a test";

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

 $dump = $matches[1];

 print "$dump";  // prints XYZ123
}

?>
codaddict
+3  A: 
$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];
  }
}
ghostdog74
+1 Regexes are overrated.
Chacha102