2011-01-13 68 views
5

我寫這個PHP代碼進行一些換人:如何使用PHP preg_replace正則表達式來查找和替換文本?

function cambio($txt){ 
    $from=array(
     '/\+\>([^\+\>]+)\<\+/', //finds +>text<+ 
     '/\%([^\%]+)\%/', //finds %text% 
    ); 

    $to=array(
     '<span class="P">\1</span>', 
     '<span>\1</span>', 
    ); 

    return preg_replace($from,$to,$txt); 
} 

echo cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.'); 

所得到這一點:

The fruit I most like is: <span class="P"> <span>apple</span> <span>banna</span> <span>orange</span> </span>. 

但是我需要找出水果的跨度標籤,就像這樣:

The fruit I most like is: <span class="P"> <span class="t1">apple</span> <span class="t2">banana</span> <span class="t3">coco</span> </span>. 

我會買一個水果,發現一個正則表達式來完成這個:-)


白衣澤維爾巴博薩的幫助下,我來到了這最後sollution:

function matches($matches){ 
    static $pos=0; 
    return sprintf('<span class="t%d">%s</span>',++$pos,$matches[1]); 
} 

function cambio($txt){//Markdown da Atípico : Deve ser usado depois do texto convertido para markdown 
    $from=array(
     '/\=>(.+?)<\=/', //finds: =>text<= 
     '/\+>(.+?)<\+/', //finds +>text<+ 
    ); 

    $to=array(
     '<span class="T">\1</span>', 
     '<span class="P">\1</span>', 
    ); 

    $r=preg_replace($from,$to,$txt); 
    return preg_replace_callback('/%(.*?)%/','matches',$r);//finds %text% 
    //'/%((\w)\w+)%/' //option 
} 
+0

內部跨度的等級(即, class =「b」)總是等於水果的第一個字母? – Ass3mbler 2011-01-13 19:43:14

+0

你是用PHP編寫自己的模板語言嗎?謹防[BobX](http://thedailywtf.com/Articles/We-Use-BobX.aspx)。 – Nathan 2011-01-13 20:05:19

+0

Ass3彙編程序,很抱歉,我不打算與內容的第一個字母建立關係。我編輯類名稱如:t1,t2和t3。 – Roger 2011-01-13 21:16:43

回答

2
<?php 


function cambio($txt){ 
    $from=array(
     '/\+>(.+?)<\+/', //finds +>text<+ 
     '/%((\w)\w+)%/', //finds %text% 
    ); 

    $to=array(
     '<span class="P">\1</span>', 
     '<span class="\2">\1</span>', 
    ); 

    return preg_replace($from,$to,$txt); 
} 

echo cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.'); 

而且有狀態版本PHP5.3

function cambio($txt) { 
    return preg_replace_callback('/\+>(.+?)<\+/', function ($matches) { 
     $txt = sprintf('<span class="P">%s</span>', $matches[1]); 

     return preg_replace_callback('/%(\w+)%/', function ($matches) { 
      static $pos = 0; 
      return sprintf('<span class="t%d">%s</span>', ++$pos, $matches[1]); 
     }, $txt); 

    }, $txt); 
} 

echo cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.'); 
1

試試這個:

function cambio($txt){ 
    $from=array(
     '/\+\>([^\+\>]+)\<\+/', //finds +>text<+ 
     '/\%(^\%)([^\%]+)\%/', //finds %text% 
    ); 

    $to=array(
     '<span class="P">\1</span>', 
     '<span class="\1">\1\2</span>', 
    ); 

    return preg_replace($from,$to,$txt); } 

echo cambio('The fruit I most like is: 
+> %apple% %banna% %orange% <+.'); 
相關問題