我正在寻找一种方法:
例如,假设这是$ string:
placeholder text placeholder text
placeholder text placeholder text
<tag1>
<tag2>
Lorem ipsum
<tag2>
Dolor sit amet
</tag1>
placeholder text placeholder text
placeholder text placeholder text
我想在<tag1>
中提取内容,删除所有<tag2>
,然后以字符串形式输出文本,替换第一个示例,使其如下所示:
placeholder text placeholder text
placeholder text placeholder text
<tag1>
Lorem ipsum
Dolor sit amet
</tag1>
placeholder text placeholder text
placeholder text placeholder text
我尝试过使用preg_replace()
:
preg_match("/<tag1>(.*?)<\/tag1>/i", $string, $matches);
foreach($matches as $value){
$code = str_replace("<tag2>", "", $value);
$string = str_replace($value, $code, $string);
}
但由于某种原因,这不起作用
答案 0 :(得分:0)
可能你需要这样的东西:
$string = "
placeholder text placeholder text
placeholder text placeholder text
<tag1>
<tag2>
Lorem ipsum
<tag2>
Dolor sit amet
</tag1>
placeholder text placeholder text
placeholder text placeholder text" ;
preg_match("/<tag1>([^\"]*)<\/tag1>/i", $string, $matches);
$formatted_part = preg_replace("/((<tag2>|<\/tag2>)[\s\t]*[\r\n]+)/", "", $matches[1]);
$new = str_replace($matches[1], $formatted_part, $string);
var_dump($new);