Replace newlines with BR tags, but only inside PRE tags

后端 未结 2 1830
青春惊慌失措
青春惊慌失措 2020-12-19 21:55

In stock PHP5, what is a good preg_replace expression for making this transformation:

replace newlines with
, but only

2条回答
  •  离开以前
    2020-12-19 22:30

    Based on something SilentGhost said (which isn't showing up here for some reason):

    1
    2
    3
    < / pre>
    
    line 1
    line 2
    line 3
    
    "; $out = "
    1
    2
    3
    < / pre>
    line 1
    line 2
    line 3
    "; function protect_newlines($str) { // \n ->
    , but only if it's in a pre block // protects newlines from Parser::doBlockLevels() /* split on
    , basically.  probably good enough */
        $str = " ".$str;  // guarantee split will be in even positions
        //$parts = preg_split('/(
    )/Umsxu',$str,-1,PREG_SPLIT_DELIM_CAPTURE);
        $parts = preg_split("/(< \s* pre .* \/ \s* pre \s* >)/Umsxu",$str,-1,PREG_SPLIT_DELIM_CAPTURE);
        foreach ($parts as $idx=>$part) {
            if ($idx % 2) {
                $parts[$idx] = preg_replace("/\n/", "
    ", $part); } } $str = implode('',$parts); /* chop off the first space, that we had added */ return substr($str,1); } assert(protect_newlines($str) === $out); ?>

提交回复
热议问题