2

I want to check in wp if post content includes gx-block class.
For example I can have

class="something_can_exists_or_not gx-block something_else" should print *true*

class="gx-block" *true*
Etc.

I have tried this but doesn't work

preg_match('/class="?.*gx-block?.*"/i', $content);

Thanks

Dave2e
  • 22,192
  • 18
  • 42
  • 50
  • Here you have answer for your question: https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word –  Jan 30 '20 at 07:46
  • you can use `strpos($content, 'gx-block')` for that as well. – mitkosoft Jan 30 '20 at 07:48
  • 2
    Since you're parsing HTML, you'd be better off [using a DOM parser](https://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php). – Jeto Jan 30 '20 at 07:53
  • Patryk Parcheta thanks. I found there a solution – Marine Gasparyan Jan 31 '20 at 06:01
  • [Parsing HTML with regex is a hard job](https://stackoverflow.com/a/4234491/372239) – Toto Jan 31 '20 at 16:35

1 Answers1

0

I don't think that regular expression is right tool for the job. As the HTML is not regular language.

Anyway you could do some think like this:

https://3v4l.org/ORKkR

const REGEX = '/class=("gx-block"|"gx-block .*"|".* gx-block")/i';


const HTML1 = '<div class="gx-block">abc</div>';
const HTML2 = '<div class="xyz">abc (gx-block) def</div>';
const HTML3 = '<div class="gx-blockhhh">abc</div>';


echo preg_match(REGEX, HTML1) ? 'true' : 'false';
echo PHP_EOL;
echo preg_match(REGEX, HTML2) ? 'true' : 'false';
echo PHP_EOL;
echo preg_match(REGEX, HTML3) ? 'true' : 'false';
echo PHP_EOL;

I would recommend doing it by DOM access instead as described here: Getting DOM elements by classname

Jan Tajovsky
  • 1,162
  • 2
  • 13
  • 34
  • A bit better than previous answer but gives true for `
    abc "gx-block" def
    `.
    – Toto Jan 31 '20 at 15:48
  • @Toto Yes. I don't think you can write such regex that will solve question. HTML is not regular language. Parsing DOM is way to go. – Jan Tajovsky Jan 31 '20 at 16:11
  • 1
    It's almost impossible, just have a look at [here](https://stackoverflow.com/a/4234491/372239) – Toto Jan 31 '20 at 16:34