игнорировать предварительные теги при использовании nl2br()

Я хочу игнорировать следующие теги при использовании nl2br. У меня есть стандартные теги pre, а также некоторые специальные теги pre, которые стилизованы. Когда я это делаю, я вставляю теги <br> внутри тегов <pre>.

string = "Here is some text

<pre>
   <xml>
     <item></item>
     <name></name>
   </xml>
</pre>

That includes new lines and carriage returns
what can i do to add <p> and <br> tags but not to the text below inside
the <pre> tags </pre>.

<pre class="brush: csharp; title: ;" title="">
    public MainPage()
{
    // select the culture (de, it, fr, tr are supported)
    var ci = new System.Globalization.CultureInfo("tr-TR"); // de-DE etc

    // this controls the UI strings
    System.Threading.Thread.CurrentThread.CurrentUICulture = ci;

    // this controls number and date formatting (optional in this sample)
    //System.Threading.Thread.CurrentThread.CurrentCulture = ci;

    // initialize the component<br>
    InitializeComponent();
}

</pre>";

вернуть это

    echo nl2br($string);

    Here is some text
    <br /><br />
    <pre>
       <xml>
         <item></item>
         <name></name>
       </xml>
    </pre>
    <br /><br />
    That includes new lines and carriage returns<br />
    what can i do to add <p> and <br> tags but not to the text below inside<br />
    the <pre> tags </pre>.<br />
    <br />
    <pre class="brush: csharp; title: ;" title="">
        <br>
    public MainPage()
    {
        // select the culture (de, it, fr, tr are supported)
        var ci = new System.Globalization.CultureInfo("tr-TR"); // de-DE etc

        // this controls the UI strings
        System.Threading.Thread.CurrentThread.CurrentUICulture = ci;

        // this controls number and date formatting (optional in this sample)
        //System.Threading.Thread.CurrentThread.CurrentCulture = ci;

        // initialize the component<br>
        InitializeComponent();
    }
    </pre>

Кажется, игнорируется наличие двух тегов <br><br>. Я думаю, что это может быть как-то связано с комментариями.

Используйте этот код.

function my_nl2br($string){

                $string = str_replace("\n", "<br />", $string);

                if(preg_match_all('/\<pre class="brush: csharp; title: ;"\>(.*?)\<\/pre\>/', $string, $match)){
                    foreach($match as $a){
                        foreach($a as $b){
                            $string = str_replace('<pre class="brush: csharp; title: ;">'.$b.'</pre>','<pre class="brush: csharp; title: ;">'.str_replace("<br />", "\n", $b)."</pre>", $string);
                        }
                    }
                }

                return $string;

            }

            echo my_nl2br($description);

Но он игнорирует возврат каретки в разделе <pre class="brush: csharp; title: ;" title="">.

вывод этого

public MainPage()
{
    // select the culture (de, it, fr, tr are supported)
    var ci = new System.Globalization.CultureInfo("tr-TR"); // de-DE etc
    // this controls the UI strings
    System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
    // this controls number and date formatting (optional in this sample)
    //System.Threading.Thread.CurrentThread.CurrentCulture = ci;
    // initialize the component
    InitializeComponent();
}

person madphp    schedule 21.11.2011    source источник


Ответы (3)


Решение из комментариев руководства PHP:

function my_nl2br($string){
$string = str_replace("\n", "<br />", $string);
if(preg_match_all('/\<pre\>(.*?)\<\/pre\>/', $string, $match)){
    foreach($match as $a){
        foreach($a as $b){
        $string = str_replace('<pre>'.$b.'</pre>', "<pre>".str_replace("<br />", "", $b)."</pre>", $string);
        }
    }
}
return $string;
}

http://www.php.net/manual/en/function.nl2br.php#100120

person djdy    schedule 21.11.2011
comment
это решение не сработало для меня. Я обновил вопрос, чтобы быть более сдержанным. - person madphp; 21.11.2011

Это старо, но, возможно, кто-то еще изучает это, так что...

В вашем примере вы используете

<pre class="brush: csharp; title: ;" title="">

но в вашем коде вы соответствуете

<pre class="brush: csharp; title: ;">
person Wang Tang    schedule 23.07.2012

Просто добавьте этот фрагмент на свою страницу

  $(document).ready(function(){
      var str_arr = document.getElementsByTagName("pre");
      for(var i = 0; i < str_arr.length; i++){
          str_arr[i].innerHTML = str_arr[i].innerHTML.replace(/<br>/g, "");
      }
  });

Это удаляет <br> из <pre>

person Siraj Alam    schedule 28.06.2018