问题描述:

Essentially, I need a means of searching a large string of text for multiple occurrences of two separate BBCode-like tags and get the data between them. For example:

$string = "Referenced section of text[ref]Reference text[/ref]";

$getStringBetween = gsb($string, "[ref]", "[/ref]";

echo $getStringBetween; //Would output "Reference Text"

I used preg_match_all to search for the string, which worked at first, but I found it to be relatively unreliable. The times it worked, it was nice, but shortly thereafter it would break and output everything between the first reference tag and the last on one array key.

Another large problem is that the [ref][/ref] tags needed to be on their own lines to work.

Moral of my story, I need some means to look for two particular text strings and get the data between them using PHP.

网友答案:

Did you try "minimal" with preg_match_all? Preg matching is usually greedy (will grab as much as it can that meets the criteria) but you can change to minimal. Use .+? or .*? as the match.

Use m for multi-line if you want to match across mulitple lines - not sure it's required base on the question, but it might be what you need.

The following should do it for you:

preg_match_all('#\[ref\](.*?)\[/ref\]#m', $string, $aMatches);
相关阅读:
Top