PHP:如何使用simple_html_dom解析器将CSS文本对齐属性添加到元素的现有内联样式属性中


PHP: How to add a CSS text-align property to an already present inline style attribute of an element using simple_html_dom parser?

我有一个字符串变量$str,它包含页面一部分的HTML。我需要将CSS属性text-align:justify添加到HTML中的所有<p>元素中(最好使用simple_html_dom解析器)。

某些<p>元素已经具有内联style属性,而其他元素则没有。所以我不能做类似的事情

$str_html = str_get_html($str);
foreach ($str->find('p') as $p) {
  $p->style='text-align:justify;';
}

因为这将使已经应用于<p>元素的任何其他样式无效。

附言:-我不能使用JQuery。我可以使用JS,但只能在万不得已的情况下使用。

您可以连接而不是重新分配

$str_html = str_get_html($str);
foreach ($str->find('p') as $p) {
  $p->style .= '; text-align:justify;';
}