[ANSWERED] html – preg_replace


Nov 20, 2022 , ,

Solution 1 :

Try with this pattern :

/<table ([^>]*?)width=["']s?d+s?(px|%)?s*["']/

The replacement $1 would preserve any other attributes (cf. (.*?) capture group) :

$text = preg_replace('/<table (.*?)width=["']s?d+s?(px|%)?s*["']/', '<table $1width="100%"', $text);

Problem :

Not sure why the code below isn’t working. Any ideas?

<table width="567"

$text = preg_replace('/<table width=["']s*d+s*(px|%)s*["']/', '<table width="100%"', $text);


Comment posted by Cid

Don’t use RegEx to parse HTML. Use a proper parser instead.

Comment posted by PHP Simple HTML DOM Parser

I see you’re using PHP.

Comment posted by Cid

Won’t work if input string is

Comment posted by EricLavault

Yep, regex won’t work anyway in this case. I think the OP would just a quick answer to his actual question and need to dig around by himself for the why’s.

Comment posted by Alex333

@ EricLavault it’s working, thank you.

Comment posted by Alex333

@Cid how would you make it work if there WAS a class or an id between table and width?

Comment posted by Cid

@EricLavault sorry, but