views:

50

answers:

4

Hey!

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!

+1  A: 

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

Oli Charlesworth
A: 

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
Turns out I was escaping it anyway, forgot to put in my code on here...
tarnfeld
+7  A: 

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
This is the only one that seemed to work out of all the answers! Thanks!
tarnfeld
regex.info also has some examples dealing with HTML tags (the 1st one): http://www.regular-expressions.info/examples.html
Peter Ajtai
+1  A: 

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