0

how can i create a preg_match_all regex pattern for php to give me this code?

<td class="class2">&nbsp;</td>
<td class="class2" align="right"><span class="DarkText">I WANT THIS TEXT</span></td>

To get me the text inside the span class? thanks!

3
  • Is this the only span class in the the text string? Commented Sep 16, 2010 at 0:06
  • 3
    xpath is much better suited to this task. Commented Sep 16, 2010 at 0:07
  • 1
    Please don't use regexes to parse HTML. It is a path to sorrow and broken code. Commented Sep 16, 2010 at 22:15

2 Answers 2

7

You can use:

preg_match_all("!<span[^>]+>(.*?)</span>!", $str, $matches);

Then your text will be inside the first capture group (as seen on rubular)

With that out of the way, note that regex shouldn't be used to parse HTML. You will be better off using an XML parser, unless it's something really, really simple.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for answer and pointing to best solution (parser). And for including the link to Bobince's famous answer.
0

You can also not use ! at start and end, and use much simpler code with T-Regx

$pattern = "<span[^>]+>(.*?)</span>"; // no delimiters :)

$string = '
<td class="class2">&nbsp;</td>
<td class="class2" align="right"><span class="DarkText">I WANT THIS 
TEXT</span></td>
';

Then just use match()->group():

$text = Pattern::of($pattern)->match($string)->group(1)->first();

$text // 'I WANT THIS TEXT'

Check it online: https://regex101.com/r/nxTvS1/1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.