简体   繁体   English

PHP-如何用另一个替换短语?

[英]PHP - How to replace a phrase with another?

How can i replace this <p><span class="headline"> with this <p class="headline"><span> easiest with PHP. 我如何用PHP最简单的方法将此<p><span class="headline">替换为此<p class="headline"><span>

$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 I alter the html from the site I want to get the class declaration from the span to the <p> tag. 在从站点更改html之前,我想要从跨度到<p>标记获取类声明。

dont parse html with regex! 不要用正则表达式解析html! this class should provide what you need http://simplehtmldom.sourceforge.net/ 此类应提供您所需的内容http://simplehtmldom.sourceforge.net/

The reason not to parse HTML with regex is if you can't guarantee the format . 不使用正则表达式解析HTML的原因是, 如果您不能保证格式 If you already know the format of the string, you don't have to worry about having a complete parser. 如果您已经知道字符串的格式,则不必担心拥有完整的解析器。

In your case, if you know that's the format, you can use str_replace 就您而言,如果您知道这是格式,则可以使用str_replace

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

Well, answer was accepted already, but anyway, here is how to do it with native DOM: 好了,答案已经被接受了,但是无论如何,这是如何使用本机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();

On a sidenote, HTML has elements for headings, so why not use a <h*> element instead of using the semantically superfluous "headline" class. 在旁注中,HTML具有用于标题的元素,因此为什么不使用<h*>元素而不是使用语义上多余的“标题”类。

Have you tried using str_replace ? 您是否尝试过使用str_replace

If the placement of the <p> and <span> tags are consistent, you can simply replace one for the other with 如果<p><span>标记的位置一致,则可以简单地将其中一个替换为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM