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!

NullUserException
  • 83,810
  • 28
  • 209
  • 234
Yannis Assael
  • 1,099
  • 2
  • 20
  • 43

2 Answers2

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.

Community
  • 1
  • 1
NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • +1 for answer and pointing to best solution (parser). And for including the link to Bobince's famous answer. – alex Sep 16 '10 at 00:16
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

Danon
  • 2,771
  • 27
  • 37