2014-11-06 18 views
0

我想提出一個腳本,用於將某些特定的標記,以已知的和有效的HTML像轉換簡單的代碼的HTML樣式

[b] bold [/b] for <span style="font-weight:bold"> bold</span> 

[color=red] red text [/color] for <span style="font-color:red"> red</span> 

[fs=15]big font[/fs] for <span style="font-size:15px"> big font</font> 

and [link=http://www.gooole.com target=new title=goole] google[/link] to be converted to 

<a href="http://www.gooole.com" title="goole">google</a> 

,也可以像它們混合的[fs = 15],這是很大的。 [顏色=紅色]紅色文本[/彩色] [/ FS]

下面是代碼,我used-

$str = preg_replace('/\[b\]/', '<span style="font-weight:bold">', $str); 
$str =preg_replace('/\[\/b\]/', '</span>', $str); 
$str= preg_replace('/\[\/fs\]/', '</span>', $str); 
$str= preg_replace('/\[fs=(.*)\]/', '<span style="font-size:$1px">', $str); 

$str= preg_replace('/\[\/color\]/', '</span>', $str); 
$str= preg_replace('/\[color=(.*)\]/', '<span style="font-color:$1">', $str); 

此代碼工作正常,如果使用未嵌套,並也適用於嵌套如果標籤唐沒有=屬性。出現問題時,我使用這樣的

[fs=15] this is big. [fs=12] this is big. [/fs] [/fs] 

它給我

<span style="font-size:15] this is big. [fs=12px"> this is big. </span> </span> 

,而應該是

<span style="font-size:15px> this is big. <span style="font-size:12px> this is big. </span> </span> 

其工作罰款

[b] hi [i] ok [/i] yes [/b] 

請建議我不知道經常性的前夫壓力。

+1

使用非貪婪匹配:'' – hjpotter92 2014-11-06 20:21:11

+0

@ hjpotter92請參閱我編輯的問題(你的代碼是工作的罰款感謝,但我還需要一個(*?)。步!) – 2014-11-06 20:29:51

+0

是否有可能只用一個preg_replace替換所有代碼,因爲我已經多次使用它了? – 2014-11-06 20:32:42

回答

1
  1. 因爲你總是更換</span>的結束標記;將它們包括在一個單一的。
  2. 您可以使用哈希映射來匹配相似的標籤結構;如[b],[i]等,並使用散列結構preg_replace_callback
  3. 使用不明確(或惰性)匹配與可能忽略case modifier。另外,使用除/以外的其他分隔符。

試試下面的代碼:

// first deal with closing tags 
$str = preg_replace('#\[/(color|b|i|fs|so|many|tags|can|go|here)\]#i', '</span>', $str); 
// now some functions; with hashmaps 
function colsize($m) { 
    $map = [ // or $map = Array(
     'color' => 'color: %s', 
     'fs' => 'size: %dpx' 
    ]; // or); 
    return sprintf('<span style="font-' . $map[$m[1]] . ';">', $m[2]); 
} 
function emph($m) { 
    $map = [ // or $map = Array(
     'b' => 'weight: bold', 
     'i' => 'style: italic' 
    ]; // or); 
    return '<span style="font-' . $map[$m[1]] . ';">'; 
} 
// using the custom functions from above now 
$str = preg_replace_callback('@\[(color|fs)=([^\]]+)\]@iU', 'colsize', $str); 
$str = preg_replace_callback('@\[([bi])\]@i', 'emph', $str); 
+0

好的,但我怎樣才能傳遞像[link = http://www.google .com target = new] Google [/ link] – 2014-11-07 04:50:01

+0

@RNKushwaha'$ str = preg_replace('#\ [/ link =(\ S +)target =([^ \]] +)\]#i','',$ str);' – hjpotter92 2014-11-07 09:20:37

1

使用非貪婪選項:

$str = preg_replace('/\[fs=(.*)\]/U', '<span style="font-size:$1px">', $str); 

,喜歡:

$str = preg_replace('/\[fs=(.*)\](.*)\[\/fs\]/U', '<span style="font-size:$1px">$2</span>', $str); 
+0

正如消息所說,一個[是開放的而不是關閉的,所以我們逃避它:'$ str = preg_replace('/\[fs=(.*)\](.*)\[\/fs\]/U' ,' $ 2',$ str);' – KyleK 2014-11-07 10:41:43

+0

感謝您的回答 – 2014-11-07 11:04:56