我想用php更改变量值的标签值;
$tag = '<string name="abs__action_bar_home_description">My old title</string>';
$new_title = 'My new title';
结果:
<string name="abs__action_bar_home_description">**My new title**</string>
答案 0 :(得分:2)
你可以使用php函数preg_replace。您的示例here
<?php
$tag = '<string name="abs__action_bar_home_description">My old title</string>';
$new_title = 'My new title';
$pattern = "/(<string[\s\w=\"]*>)([\w\s]*)(<\/string>)/i";
$replacement = "$1".$new_title."$3";
$result = preg_replace($pattern, $replacement ,$tag);
echo $result;
?>
答案 1 :(得分:1)
以下是如何在没有正则表达式的情况下实现相同功能,但使用DOMDocument和DOMXPath:
$tag = '<string name="abs__action_bar_home_description">My old title</string>';
$new_title = 'My new title';
$dom = new DOMDocument('1.0', 'UTF-8');
@$dom->loadHTML($tag, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
$links = $xpath->query('//string[@name="abs__action_bar_home_description"]');
foreach($links as $link) {
$link->nodeValue = $new_title;
}
echo $dom->saveHTML();
请参阅IDEONE demo
'//string[@name="abs__action_bar_home_description"]'
xpath表示您希望获取string
标记,其属性name
的值为abs__action_bar_home_description
。
如果您加载HTML文件,则可以使用类似
的内容$dom->loadHTMLFile("http://www.example.com/content.html");