2010-07-03 78 views
0

你好,我想做到以下几点:的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,但找不到工作解决方案。

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

而且|第一级应该变成〜。

任何想法?

问候

+0

这是功课?到目前为止,你有什么? – 2010-07-03 18:45:44

+1

您是否有一个一般模式?你的例子非常具体。 – casablanca 2010-07-03 18:50:36

+0

那么我的主要问题是嵌套。如果我能得到一个数组或者与stackoverflow是一个{很酷|伟大的}网站和stackoverflow是{best |最大}作为价值将很容易修复其余。 – brechtvhb 2010-07-03 19:34:09

回答

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)) . '}'; 
+0

'trim'在字符串的末尾删除了太多的'}'。 – salathe 2010-07-03 19:20:15

+0

这似乎并没有工作... 在$价值做了回声,它吐出这个: {stackoverflow是一个很酷的网站| stackoverflow是最好的最大的 – xil3 2010-07-03 19:22:12

+0

这不是真正的工作;( – brechtvhb 2010-07-03 19:33:02