我有一个HTML代码,并希望仅用空格替换破折号,但仅在特定标记之间。
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname ?.*>('d*)[-*]('d*)<'/$tagname>/";
$replace = " ";
$string = preg_replace($pattern, $replace, $string);
}
代码示例:
<div class="xxx">
<a href="/start">start</a>
<a href="/start/world">World</a>
<a href="/start/world/fantastic-yyy-zz">Fantastic-yyy-zz</a>
peter-hey
</div>
结果:虽然'peter hey'没有破折号,但更重要的是标签的值。
<div class="xxx">
<a href="/start">start</a>
<a href="/start/world">World</a>
<a href="/start/world/fantastic-yyy-zz">Fantastic yyy zz</a>
peter-hey
</div>
您不需要正则表达式来执行此任务:
$contents = '<div class="xxx">
<a href="/start">start</a>
<a href="/start/world">World</a>
<a href="/start/world/fantastic-yyy-zz">Fantastic-yyy-zz</a>
peter-hey
</div>';
$doc = new DOMDocument();
$doc->loadXML($contents);
$tagName = 'a';
$tags = $doc->getElementsByTagName($tagName);
foreach ($tags as $tag) {
$newValue = str_replace('-', ' ', $tag->nodeValue);
$tag->nodeValue = $newValue;
}
echo $doc->saveHTML();
演示:http://ideone.com/rI6k8b
@zerkms感谢您的帮助和耐心,几乎完全按照您所说的进行了尝试,但它显示了警告并且没有做出更改。
Warning: DOMDocument::loadXML(): Extra content at the end of the document in Entity
代码:function process(&$vars) {
$theme = get_theme();
if ($vars['elts']['#xxx'] == 'main') {
$vars['bread'] = $theme->page['bread'];
/*add code*/
$doc = new DOMDocument();
$doc->loadXML($vars['bread']);
$tagName = 'a';
$tags = $doc->getElementsByTagName($tagName);
foreach ($tags as $tag) {
$newValue = str_replace('-', ' ', $tag->nodeValue);
$tag->nodeValue = $newValue;
}
echo $doc->saveHTML();
/*end add code*/
}
}
@zerkms,我给你的答案和你真正给出的正确答案一样有效。我也很惊讶地说,我发现了一些有趣的答案:
代码查找信息
$tagname = 'a';
$pattern = "/<$tagname ?.*>(.*)'-+(.*)<'/$tagname>/";
$matches = "";
preg_match($pattern, $contents, $matches);
CODE TO CHANGE:因为我只有一段代码,所以我真的不需要检查标签是否为'a'。
$pattern = "/>(.*)'-+(.*)'-+(.*)</";
$replace = ">$1 $2 $3<";
$res = preg_replace($pattern, $replace, $contents);
//$contents是包含代码的字符串。
希望它真的能帮助到一些人。