0

我正在寻找一种方法:

  1. 从变量中提取一段文本
  2. 从提取的文本中删除某种类型的所有标签
  3. 输出没有特定标签的结果。(下面的例子)

例如,假设这是 $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);
}

但这由于某种原因不起作用

4

1 回答 1

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);
于 2013-05-09T22:39:08.527 回答