How do I parse a string for a particular delimited section within PHP?
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 assi开发者_StackOverflow社区stance.
What is the best way to pull the fragment in between the [{ and }]? Thanks in advance for your help!
<?php
$str = "[{XYZ123}] This is a test";
if(preg_match('/\[{(.*?)}\]/',$str,$matches)) {
$dump = $matches[1];
print "$dump"; // prints XYZ123
}
?>
$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];
}
}
The regex would be (?=\[\{).*(?=\}\])
, though I don't know if php supports look aheads.
精彩评论