Reputation: 1
I can't seem to figure out exactly how to get a certain portion of text I need out of a larger block. I need to be able to grab a string between a : and a ( in a regular block of text while parsing an email. An example is below. I know a bit about preg_match and I figured that was the answer, but can't seem to get that to work either. Any help would be appreciated as searches of here and Google have turned up nothing.
For GC3J26P: Wise Lake II (Traditional)
I need just the text between the : and the beginning parentheses. Thanks for any help.
Upvotes: 0
Views: 56
Reputation: 606
Here it is: I used a 'named sub-pattern' (named it "name", but could be called almost anything)...
$str="For GC3J26P: Wise Lake II (Traditional)";
preg_match('/:(?P<name>[\S\s]+)\(/', $str, $matches);
echo $matches["name"];
Upvotes: 0
Reputation: 34608
Since you say you've tried and not managed to get anything going, try this:
$str = "For GC3J26P: Wise Lake II (Traditional)";
preg_match('/(?<=:).*(?=\()/', $str, $str);
if ($str) echo $str[0];
If you're new to the murky - yet beautiful - world of REGEX, allow me to explain what's happening here.
It's all about the pattern. Our pattern defines what is and is not acceptable in what we match - i.e. capture.
More than that, it even states what should immediately precede and procede our match. These are called look-behind and look-ahead assertions, respectively. These assertions are anchors for our matching points - they do not contribute to the captured match itself.
So our pattern translates as:
1) begin the match after a colon (but do not include the colon in the match)
2) then allow and capture any character (barring line breaks and certain other spacial characters), zero or more times
3) match up to (but not including) an opening bracket
Our pattern is what's called greedy. In our case, this means that, should the sub-string you wish to match itself contain a colon or bracket, this will be no problem and won't break things. As long as there is a valid match available starting from SOME colon, and up to SOME opening bracket, all's fine. (Note: greedy behaviour can be modified, if required).
There's far, far more to REGEX and you either love it hate it. If you're interested, I suggest reading up on it. It's very satisfying once you get into it.
And with that, it's bed time.
Upvotes: 3
Reputation: 9315
You can try this:
$string = 'For GC3J26P: Wise Lake II (Traditional)';
preg_match('/\:(.*?)\(/', $string, $matches);
echo $matches[0]; // : Wise Lake II (
echo $matches[1]; // Wise Lake II
Upvotes: 0