Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match a certain HTML element

I'm trying to write a regular expression for matching the following HTML.

<span class="hidden_text">Some text here.</span>

I'm struggling to write out the condition to match it and have tried the following, but in some cases it selects everything after the span as well.

$condition = "/<span class=\"hidden_text\">(.*)<\/span>/";

If anyone could highlight what I'm doing wrong that would be great.

like image 332
diggersworld Avatar asked Jul 04 '26 03:07

diggersworld


2 Answers

You need to use a non-greedy selection by adding ? after .* :

$condition = "/<span class=\"hidden_text\">(.*?)<\/span>/";

Note : If you need to match generic HTML, you should use a XML parser like DOM.

like image 118
HoLyVieR Avatar answered Jul 05 '26 18:07

HoLyVieR


You shouldn’t try to use regular expressions on a non-regular language like HTML. Better use a proper HTML parser to parse the document.

See the following questions for further information on how to do that with PHP:

  • How to parse HTML with PHP?
  • Best methods to parse HTML
like image 43
Gumbo Avatar answered Jul 05 '26 17:07

Gumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!