with this

easiest way with...">

PHP - How to replace a phrase with another?

How can I replace this <p><span class="headline"> with this <p class="headline"><span> easiest way with PHP.

 $data = file_get_contents("http://www.ihr-apotheker.de/cs1.html"); $clean1 = strstr($data, '<p>'); $str = preg_replace('#(<a.*>).*?(</a>)#', '$1$2', $clean1); $ausgabe = strip_tags($str, '<p>'); echo $ausgabe; 

Before changing the html from the site, I want to get the class declaration from the range in the <p> .

+2
source share
4 answers

Have you tried using str_replace ?

If the placement of the <p> and <span> tags is consistent, you can simply replace one with another

 str_replace("replacement", "part to replace", $string); 
0
source

dont parse html with regex! this class should provide what you need http://simplehtmldom.sourceforge.net/

+3
source

Reason not to parse HTML with regex if you cannot guarantee the format . If you already know the format of the string, you need not worry about having a full parser.

In your case, if you know this format, you can use str_replace

str_replace('<p><span class="headline">', '<p class="headline"><span>', $data);

+1
source

Well, the answer has already been accepted, but in any case, here's how to do it with the native DOM:

 $dom = new DOMDocument; $dom->loadHTMLFile("http://www.ihr-apotheker.de/cs1.html"); $xPath = new DOMXpath($dom); // remove links but keep link text foreach($xPath->query('//a') as $link) { $link->parentNode->replaceChild( $dom->createTextNode($link->nodeValue), $link); } // switch classes foreach($xPath->query('//p/span[@class="headline"]') as $node) { $node->removeAttribute('class'); $node->parentNode->setAttribute('class', 'headline'); } echo $dom->saveHTML(); 

There are elements for headings in the HTML side code, so why not use the <h*> element instead of using a semantically superfluous heading class.

+1
source

Source: https://habr.com/ru/post/1444537/


All Articles