两个html标签之间的PHP字符串替换 [英] PHP String Replace between two html tags
本文介绍了两个html标签之间的PHP字符串替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试替换 html 文档中两个标签之间的文本.我想替换任何没有用 < 括起来的文本.和 >.我想用 str_replace 来做到这一点.
I am trying to replace text between two tags in a html document. I want to replace any text that isn't enclosed with a < and >. I want to use str_replace to do this.
php $string = '
一些我想替换的文本</h1><p>一些我想替换的内容</p>';
$text_to_echo = str_replace("Bla","Da",$String);
echo $text_to_echo;
推荐答案
试试这个:
<?php
$string = '<html><h1> some text i want to replace</h1><p>
some stuff i want to replace </p>';
$text_to_echo = preg_replace_callback(
"/(<([^.]+)>)([^<]+)(<\\/\\2>)/s",
function($matches){
/*
* Indexes of array:
* 0 - full tag
* 1 - open tag, for example <h1>
* 2 - tag name h1
* 3 - content
* 4 - closing tag
*/
// print_r($matches);
$text = str_replace(
array("text", "want"),
array('TEXT', 'need'),
$matches[3]
);
return $matches[1].$text.$matches[4];
},
$string
);
echo $text_to_echo;
这篇关于两个html标签之间的PHP字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文