使用以下代码尝试使用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>
实例?
由于
答案 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();
答案 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);