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
  • 24,994
  • 39
  • 109
  • 145

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
  • 81,190
  • 27
  • 202
  • 228
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
  • 14,939
  • 3
  • 30
  • 42
1

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

Oliver Charlesworth
  • 260,367
  • 30
  • 546
  • 667
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,268
  • 2
  • 18
  • 15