Использование SimpleHtmlDom, как удалить и заменить определенный атрибут

В настоящее время я использую этот HTML DOM PARSER, используя php: http://simplehtmldom.sourceforge.net/

Я смущен тем, как удалить и заменить выбранный атрибут href="style.css" , я хочу заменить ссылку на "index/style.css" , если я вставляю только

индекс/

или заменить весь атрибут из всего HTML-кода?

Это должно сделать это:

 $doc = str_get_html($code); foreach ($doc->find('a[href]') as $a) { $href = $a->href; if (/* $href begins with a relative URL path */) { $a->href = 'index/'.$href; } } $code = (string) $doc; 

Вы также можете использовать собственную библиотеку DOM для PHP :

 $doc = new DOMDocument(); $doc->loadHTML($code); $xpath = new DOMXpath($doc); foreach ($xpath->query('//a[@href]') as $a) { $href = $a->getAttribute('href'); if (/* $href begins with a relative URL path */) { $a->setAttribute('href', 'index/'.$href); } } $code = $doc->saveHTML(); 

В официальном руководстве есть несколько примеров, которые в основном охватывают все, что вам нужно:

http://simplehtmldom.sourceforge.net/manual.htm

Если у вас есть проблемы с определенным шагом, не стесняйтесь обновлять свой вопрос и предоставлять часть своего кода.

 $html = str_get_html($string); if ($html){ // Verify connection, return False if could not load the resource $e = $html->find("a"); foreach ($e as $e_element){ $old_href = $e_element->outertext; // Do your modification in here $e_element->href = affiliate($e_element->href); // for example I replace original link by the return of custom function named 'affiliate' $e_element->href = ""; //remove href $e_element->target .= "_blank"; // I added target _blank to open in new tab // end modification $html = str_replace($old_href, $e_element->outertext, $html); // Update the href }