将简单代码转换为html样式


Convert simple codes to html styles

我正在制作一个脚本,用于将一些特定标签转换为已知且有效的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]那样混合它们,这太大了。[color=red]红色文本[/color][/fs]

这是我使用的代码-

$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. 由于您总是将结束标记替换为</span>;将它们包含在一个单独的列表中
  2. 您可以使用散列映射来匹配类似的标签结构;如[b][i]等并且在preg_replace_callback中使用散列结构
  3. 使用unreedy(或lazy)匹配和可能的ignorecase修饰符。此外,请使用除/之外的其他分隔符

尝试以下代码:

// 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 );

使用非贪婪选项:

$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 );