【问题标题】:preg_replace with attribute valuespreg_replace 用属性值
【发布时间】:2013-05-12 20:55:23
【问题描述】:

我使用 preg_replace 来解码 bbcode,我使用 (.*?) 来获取属性值。

我想用font-size:\10px; (font-size:(.*?)0px;) 替换它,例如,如果属性值为7,那么字体大小将为70。但它认为我想要值\10。我该怎么做才能将属性值和0分开?

是否可以像'font-size:'.\1.'0px;' 或类似的东西将属性值与零分开?

【问题讨论】:

  • 发布样本输入输出和您的 preg_replace 调用。
  • preg_replace call = '/\[size\="?(.*?)"?\](.*?)\[\/size\]/ms' replace with = '<span style="font-size:\\${1}0px">\\2</span>' sample output = <span style="font-size:70px;">blalba</span>(假设值为 7)
  • 请提供一个示例输入,以便我可以尝试您的示例并为您提供一些建议。

标签: php preg-replace


【解决方案1】:

\${1}0here 记录的解决方案。

[编辑]

我尝试了所有可能的反斜杠,不得不说.. 对我来说这绝对是没有意义,那

echo preg_replace('/(2.)/', '\\${1}', '12345');

输出1${1}45

但我找到了一种解决方案,heredoc

$a = <<<ABC
\${1}
ABC;
echo preg_replace('/(2.)/', $a, '12345');

【讨论】:

  • '&lt;span style="font-size:\${1}0px"&gt;\2&lt;/span&gt;' 我试过这个,但它输出&lt;span style="font-size:${1}0px"&gt;
  • 应该是'&lt;span style="font-size:\\${1}0px"&gt;\\2&lt;/span&gt;'
  • 似乎不起作用,就像使用单个反斜杠一样
  • 关于反斜杠的奇怪 PHP 行为。将 PHP 与 C(或其他著名语言)进行比较。 [PHP] ideone.com/rU9lxQ [C] ideone.com/lCBEGQ
  • @Matmarbon 好吧,至少这次我得到了不同的输出,带有 3 个反斜杠的输出变成了 `font-size:\70px;'
【解决方案2】:

应用于此文本:

$str = <<< EOD
[size="4"]test1[/size]
[size="4]test2[/size]
[size=4"]test3[/size]
[size=4]test4[/size]
EOD;
$pattern = '@\\[size=("?)(\\d++)\\1\\](.*?)\\[/size\\]@s';

preg_replace:

$replace = '<span style="font-size:${2}0px;">$3</span>';    
echo preg_replace($pattern,$replace,$str);

preg_replace_callback:

$replace = function ($matches) {
    return sprintf('<span style="font-size:%s0px;">%s</span>',
        $matches[2],
        $matches[3]
    );
};     
echo preg_replace_callback($pattern,$replace,$str);

结果:

<span style="font-size:40px;">test1</span>
[size="4]test2[/size]
[size=4"]test3[/size]
<span style="font-size:40px;">test4</span>

【讨论】:

    【解决方案3】:

    天哪... PHP 手册造成了很大的混乱...

    关于这段代码:

    echo preg_replace('/^(1)(2)(3)(4)(5)$/', $r, '12345');
    

    预期输出:

    12345!!12345!!
    

    使用heredoc时:

    $r = <<< EOD
    $0!!\${1}2\${3}4$5!!
    EOD;
    

    但是,不使用heredoc:

    $r = '$0!!${1}2${3}4$5!!';
    

    是的,不需要反斜杠

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多