Regex problem - finding first occurrence

This is quite difficult to explain, so please bare with me.

I’m trying to extract all characters situated between the first occurrence of 00ff0216 and the first occurence of 00ff in the string below:

003c00ff0216356f7265616d746400ff58040402180800ff0458 (note the two 00ff’s after 00ff0216 - I want everything up until the first occurrence of 00ff [in blue], not the second [in purple])

At the moment I have:


 $string = "003c00ff0216356f7265616d746400ff58040402180800ff0458";
 
 preg_match_all("/00ff0216([^<]+)00ff/i",$string,$matches);
 
 echo $matches[1][0];

But the above code is not returning the characters between 00ff0216 and the FIRST 00ff - which would be 356f7265616d7464. It’s ignoring the first 00ff and returning all characters up to the last occurrence of 00ff. Unfortunately, I cannot specify more characters for the end ‘flag’ (which would be much easier), and can only use 00ff.

Could somebody please explain what regular expression would work for this? I can’t use splitting/explode functions because in my final script, there will be more 00ff’s either side of the code.

Any help would be appreciated.

Thanks! :confused:

That’s because your expression is greedy (it doesn’t stop at the first match). This can be fixed in three ways:

  1. Add a question mark to font=courier new[/font], making it font=courier new[/font].

  2. Add the U modifier to the end of the pattern.

  3. Use the inline modifier U, making it font=courier new[/font].

Which method you choose is up to you. Just note that you shouldn’t use both the U modifier and the question mark, since that’ll make the pattern behave exactly as it does now. :slight_smile:

Excellent! Thanks Lilleman!! :slight_smile: