我想用在$tagsReplace数组中定义的内容替换元素内容,但是preg_replace有问题,我当前的ode:

$tagsReplace = array(
    'header' => 'header',
    'tag1' => 'this is tag1',
    'tag2' => 'this is tag2',
    'tag3' => 'this is tag3',
    'footer' => 'footer',
);

$content = '
<!DOCTYPE html>
<hthml>
<header data-edit="true" data-tag-id="header"></header>
<div data-edit="true" data-tag-id="tag1"></div>
<div data-edit="true" data-tag-id="tag2"></div>
<div data-edit="true" data-tag-id="tag3"></div>
<footer data-edit="true" data-tag-id="footer"></footer>
</html>
';

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($content);
$xpath = new DomXpath($dom);

foreach ($xpath->query('//*[@data-edit="true"]') as $rowNode) {
    $tagID = $rowNode->getAttribute('data-tag-id');
    $content = preg_replace('/(<div.*?data-edit="true"[^>]*>)(.*?)(<\/div>)/i', '$1'. $tagsReplace[$tagID] . '$3', $content);
}
echo $content;

我想要的是这样输出:
<!DOCTYPE html>
<hthml>
<header data-edit="true" data-tag-id="header">header</header>
<div data-edit="true" data-tag-id="tag1">this is tag1</div>
<div data-edit="true" data-tag-id="tag2">this is tag2</div>
<div data-edit="true" data-tag-id="tag3">this is tag3</div>
<footer data-edit="true" data-tag-id="footer">footer</footer>
</html>

电流输出为:
 <!DOCTYPE html>
<hthml>
<header data-edit="true" data-tag-id="header"></header>
<div data-edit="true" data-tag-id="tag1">footer</div>
<div data-edit="true" data-tag-id="tag2">footer</div>
<div data-edit="true" data-tag-id="tag3">footer</div>
<footer data-edit="true" data-tag-id="footer"></footer>
</html>

Soo包含attibute data edit=“true”和data tag id的所有元素都必须用在arra$tagsReplace中定义的tagid值替换其中的内容。

最佳答案

因为你正在指定
你的preg_匹配模式中的div
我们知道第一个元素以header开头,所以它不匹配
所以只需将preg_match模式开头的“div”替换为(.*?)匹配标题甚至其他单词。
这:
$content=preg_replace('/(]>)(*?)(

)/i','$1'。$tagsReplace[$tagID]。'$3',$content);
变成:
$content=preg_replace('/(<(*?)data edit=“true”[^>]>)(.?)(
)/i','$1'。$tagsReplace[$tagID]。'$3',$content);
另一个选项是可用的,您可以使用preg_replace_callback(模式、函数、主题)神奇地执行您想要的操作,下面是一个对我有效的解决方案:
$content = '
<!DOCTYPE html>
<hthml>
<header data-edit="true" data-tag-id="header"></header>
<div data-edit="true" data-tag-id="tag1"></div>
<div data-edit="true" data-tag-id="tag2"></div>
<div data-edit="true" data-tag-id="tag3"></div>
<footer data-edit="true" data-tag-id="footer"></footer>
</html>
';

$pattern = '/<(.+) data-edit="true" data-tag-id="(.*)"(.*?)>(.*?)<\/(.+)>/';
$another = preg_replace_callback($pattern, function($matches){
    $tagsReplace = array(
        'header' => 'header1',
        'tag1' => 'this is tag1',
        'tag2' => 'this is tag2',
        'tag3' => 'this is tag3',
        'footer' => 'footer',
    );
    return '<'.$matches[1].' data-edit="true" data-tag-id="'.$matches[2].'"'.$matches[3].'>'.$tagsReplace[$matches[2]].'<\/'.$matches[5].'>/';
}, $content);
# before the replacement
print_r($content);
echo '\n';
// another holds the content after replacement
print_r($another);

07-24 18:30