PHP正则表达式:匹配最接近的一个

I have a string like this

<div><span style="">toto</span> some character <span>toto2</span></div>

My regex:

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

I used preg_match and it returns the entire string

<span style="">toto</span> some character <span>toto2</span>

I want it returns:

<span style="">toto</span>
and
<span>toto2</span>

What do I need to do to achieve this? Thanks.

How about this:

/(<span[^>]*>)(.*?)(<\/span>)/

Check the docs here at PHP preg_match Repetition:

By default, the quantifiers are "greedy", that is, they match as much as possible

and

However, if a quantifier is followed by a question mark, then it becomes lazy, and instead matches the minimum number of times possible

Even though I guess all previous answers are correct, I just want to add that as you only want to capture the whole expressions (i.e. from to ) you don't have to capture eveything inside the regexp with () The following does what you expect without capturing additional expressions

/(<span\w*[^>]*>[^<]*<\/span>)/

(tested on http://rubular.com/)

EDIT : of course there might be some differences between PHP and ruby regexp implementations, but the idea is the same :)