如何使用PHP preg_replace将<span * =“”style =“font-weight:bold;”> * </span>替换为<strong> * </strong>?

时间:2011-10-26 14:05:32

标签: php html regex

使用以下代码尝试使用HTML文件进行正则表达式:

<body style=""><p class="Normal" style="direction:ltr;unicode-bidi:normal;"><span class="Normal-H"><span class="-H" style="font-weight:bold;"></span><span class="-H" style="font-weight:bold;">Some bold text</span></span></p><p class="Normal" style="direction:ltr;unicode-bidi:normal;"><span class="Normal-H"><span class="-H" style="font-style:italic;"></span><span class="-H" style="font-style:italic;">Some italic text</span></span></p></body></html>

请注意<span class="-H" style="font-weight:bold;">Some bold text</span>

我目前正在使用PHP preg_replace '/<span class="-H" style="font-style:italic;">(.*?)<\/span>/'替换为<strong>Some bold text</strong>,但这仅限于spans,类"-H"

如何使用<span>替换包含属性style="font-weight:bold;"任何 <strong>Bold text</strong>实例?

由于

4 个答案:

答案 0 :(得分:3)

您的RegEx应该是:

%^(<span(.*?)style="font-weight:bold;"(.*?)>(.*?)</span>)$% // % is the delimeter.

您应该将文本放入强标记中,如下所示:

<strong>$4</strong>

http://www.regular-expressions.info/javascriptexample.html

进行测试
$text = '<span class="-H" style="font-weight:bold;">Some bold text</span>';
$regex = '%^(<span(.*?)style="font-weight:bold;"(.*?)>(.*?)</span>)$%';
$replace = '<strong>$4</strong>';
echo preg_replace($regex, $replace, $text);

答案 1 :(得分:3)

正则表达式可能非常困难。但是这个解决方案呢?

$element = simplexml_load_string('<span class="-H" style="font-weight:bold;">Some boldtext</span>');
$attributes = $element->attributes();

echo strpos($attributes->class, ':') ? strstr($attributes->class, ':', false) : $attributes->class;
echo $element;

答案 2 :(得分:1)

您可以使用DOM解析器(例如DOMDocument)代替RegEx,以使用<span>标记替换正确的<strong>标记。它可能比RegEx更容易使用/适应。

<?php
$dom = new DOMDocument;
@$dom->loadHTML('<body style=""><p class="Normal" style="direction:ltr;unicode-bidi:normal;"><span class="Normal-H"><span class="-H" style="font-weight:bold;"></span><span class="-H" style="font-weight:bold;">Some bold text</span></span></p><p class="Normal" style="direction:ltr;unicode-bidi:normal;"><span class="Normal-H"><span class="-H" style="font-style:italic;"></span><span class="-H" style="font-style:italic;">Some italic text</span></span></p></body></html>');
$xPath = new DOMXPath($dom);
$spans = $xPath->query('//span');
foreach($spans as $span){
  if($span->hasAttribute('style')){
    if(strstr($span->getAttribute('style'), 'font-weight:bold') !== FALSE){
      $newSpan = $dom->createElement('strong', $span->nodeValue);
      $span->parentNode->replaceChild($newSpan, $span);
    }
  }
}
echo $dom->saveHTML();

DEMO:http://codepad.org/bIyAlXUf

答案 3 :(得分:1)

我认为您可以获得下面给出的适当结果,

$text    = '<span class="-H" style="font-weight:bold;">Some bold text</span>';
$regex   = '/<span(.*?)style="font-weight:bold;"(.*?)>(.*?)<\/span>/gi'; //if you use only first 
$replace = '<strong>$4</strong>';
echo preg_replace($regex, $replace, $text);