0

I am quite new to the whole Regex thing and tried to do a preg_match_all in PHP which, kind of the results I wanted but the problem is it matches everything after what I actually wanted... like so:

String: This is something <code>Some code here</code> and more Match from Regex: <code>Some code here</code> and more Wanted match from Regex: <code>Some code here</code>

Here is my regular expression that I'm using: /<code>(.*)<\/code>/

I think its something to do with the beginning and ending / delimiters but I'm not entirely sure.

Any help would be appreciated, thanks!

tarnfeld
  • 25,992
  • 41
  • 111
  • 146

4 Answers4

8

The star is greedy, meaning it will match as much as it can. Use

(.*?)

instead, making it lazy. You can also use negated character classes:

!<code>([^<]*)</code>!

EDIT: Since mvds deleted his/her answer, here's a tip: You can avoid having to escape the slash (/) if you don't use it as a delimiter, like I did above ^ (used ! )

Here's a good resource on regex:
http://www.regular-expressions.info/repeat.html

NullUserException
  • 83,810
  • 28
  • 209
  • 234
2

you want to make the .* be non greedy. If you put a ? after that part of the pattern it will match everything up to the next part of the regex that matches. So make the regex /<code>(.*?)<\/code>/

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
1

You need to disable greediness. Use .*? instead, I believe.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0

I'm not 100% sure how this is even compiling - you need to escape the second / as so:

/<code>(.*)<\/code>/

So that PHP recognises it as a character to match rather than the end of the regular expression (I think it may be compiling as a substitute regex).

Oren
  • 3,273
  • 2
  • 19
  • 15