Bir
  dört boşluk girintili metin bloklarını dönüştürmek için PHP kodu 

3 Cevap php

PHP çok iyi değilim ve bu (dört boşluk girintili metin bloğu) döner bir PHP işlevi istiyorum:

    printf("goodbye world!");  /* his suicide note
                                  was in C */

Bu içine:

<pre><code>    printf("goodbye world!");  /* his suicide note
                              was in C */</code></pre>

Bozulmamış tüm diğer satırları bırakmak.

Bu Markdown ne olduğunu. I this PHP port of Markdown (function doCodeBlocks() bakınız) bulundu, ama ben sadece bu tek fonksiyon istiyorum, tüm Markdown dosyayı kullanmak istemiyorum.

Birisi bu işe almak için gereken minimum PHP kodu ile bana sağlayabilir? Yani bunu yapabilirsiniz:

<?php echo markdownPre('Here goes some code:

    var x = 1, y = 2;
    alert(x + y);

That should be a pre block.'); ?>

3 Cevap

Kenny'nin ifadesi çalışmasına rağmen, ben esneklik için geri arama ile değiştirilmesi öneririm:

function markdownPre($in) {
    if(is_array($in)) {
        $code = $in[0];
        // post-process the code, e.g. remove leading spaces
        $code = preg_replace('~^(\x20{4}|\t)~m', '', $code);
        return "<pre>$code</pre>";
    }

    return preg_replace_callback('~(
        ^
        (\x20{4} | \t)
        (.+)
        \n
    )+~mx', __FUNCTION__, $in);
}

"Post-process" aşamasında, örneğin, dizim ilginç şeyler yapabilirsiniz.

Ben denemedim, ama preg_replace regex can düşünüyorum

/((?:^(?: {4}|\t).*$\n+)+)/m

ile <pre><code>$1</code></pre>.

Ben doğru sorunu anlamıyorum. Eğer böyle bir şey istiyorsun -

function markdownPre($str){ return '< pre>< code>'.$str.''; }

Bu dönecektir

<pre><code>    printf("goodbye world!");  /* his suicide note
                              was in C */</code></pre>

Eğer geçerseniz

echo markdownPre('printf("goodbye world!"); /* his suicide note was in C */')

buna.