Php Replace in string Preg_match

93 views Asked by At

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

1

There are 1 answers

3
Jan Tajovsky On

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