用原始字符串替换字符串

时间:2013-04-11 21:12:42

标签: php string

我有一个WYSIWYG编辑器,我的客户想要使用类似Wordpress短代码的类似模式。

有效地,客户希望做类似的事情:

 [.class_name]
      /// Some content here
 [/close_container]

我能够通过使用str_replace()轻松替换[/ close_container],但是因为class_name将随着每个使用的短代码而改变(比如它是[.green_block]我首先必须捕获green_block,然后替换整个[。 green_block]和<div class='green_block'>。没有预定义的类列表,所以我对如何处理它有点无能为力。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

使用

$formated_string= preg_replace("/\[\.(\w\-\s)\]/", "$1", $entire_string);

...沙洛姆

答案 1 :(得分:1)

这正是正则表达式最适合:

$string = preg_replace('/\[\.(\w+)\]/i', '<div class="$1">', $string);
$string = str_replace('[/close_container]', '</div>', $string);

显然上面没有任何错误检查,因此很容易构造格式错误的HTML。通过一些额外的工作,你可以解决这个问题并构建一些非常稳定的东西。

答案 2 :(得分:1)

使用有限的允许输入集(并且让客户端需要在HTML实体中编写它们,如果不是特殊代码字符&#91; [/ &#93;]:

strtr($string, array(
    '[/close_container]' => '</div>', 
    '[.' => '<div class="', 
    ']' => '">'
));

Works like a charm.

相关问题