我有一个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>
结果:虽然&#39;彼得嘿&#39;没有破折号,标签的价值就更重要了。
<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>
答案 0 :(得分:6)
您不要需要此任务的正则表达式:
$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();
答案 1 :(得分:0)
@zerkms感谢您的帮助和耐心,几乎完全按照您的说法进行了尝试,但它显示了警告并且没有做出改变。
Warning: DOMDocument::loadXML(): Extra content at the end of the document in Entity
CODE:
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*/
}
}
答案 2 :(得分:0)
寻找信息的代码
$tagname = 'a';
$pattern = "/<$tagname ?.*>(.*)\-+(.*)<\/$tagname>/";
$matches = "";
preg_match($pattern, $contents, $matches);
代码更改:因为我只有一段代码,所以我真的不需要检查标签是'a'。
$pattern = "/>(.*)\-+(.*)\-+(.*)</";
$replace = ">$1 $2 $3<";
$res = preg_replace($pattern, $replace, $contents);
// $ contents是我的代码字符串。
希望这对某人有帮助。