preg_replace问题

时间:2010-07-03 18:39:50

标签: php preg-replace

您好我正在尝试执行以下操作:

假设我有一个像这样的输入字符串

{stackoverflow is a {cool|great} website|stackoverflow is the {best|greatest}}. {stackoverflow is for {cool|great} coders|stackoverflow is the {best|greatest} site for coders}

如何使用PHP

将其转换为以下格式
{stackoverflow is a [cool|great] website~stackoverflow is the [best|greatest]}. {stackoverflow is for [cool|great] coders~stackoverflow is the [best|greatest] site for coders}

我正在使用preg_replace但我找不到可行的解决方案。

总结一下: 嵌套的{应该变成[。

和|在第一级应该变成〜。

有什么想法吗?

此致

1 个答案:

答案 0 :(得分:0)

不需要preg_replace;)

$value = '{stackoverflow is a {cool|great} website|stackoverflow is the {best|greatest}}';
$map = array( '{' => '[', '}' => ']', '~' => '|' );
$value = '{' . str_replace( array_keys($map), array_values($map), substr($value, 1, -1) ) . '}';