使用Preg_Replace使用php css将文本替换为其他文本

时间:2015-12-17 15:17:18

标签: php html regex

css造型

<style>
.red { color: red; }
.blue { color: blue;}
</style>

php中的代码

<?php
$string = 'I want a [red]red[/red] apple and a [blue]blue[/blue] umbrella';
$patterns = array();
$patterns[0] = '/[red]/';
$patterns[1] = '/[/red]/';
$patterns[2] = '/[blue]/';
$patterns[3] = '/[/blue]/';
$replacements = array();
$replacements[0] = '<span class="red">';
$replacements[1] = '</span>';
$replacements[2] = '<span class="blue">';
$replacements[3] = '</span>';
echo preg_replace($patterns, $replacements, $string);
?>

但它并没有带我价值,也就是说,不会改变影响。我试过删除&#39; \&#39;但仍然无法正常工作

2 个答案:

答案 0 :(得分:2)

我相信模式应该如下......

$patterns[0] = '/\[red\]/';
$patterns[1] = '/\[\/red\]/';
$patterns[2] = '/\[blue\]/';
$patterns[3] = '/\[\/blue\]/';

答案 1 :(得分:0)

您需要在正则表达式中转义特殊字符([/)。这是工作代码:

<?php
$string = 'I want a [red]red[/red] apple and a [blue]blue[/blue] umbrella';
$patterns = array();
$patterns[0] = '/\[red\]/';
$patterns[1] = '/\[\/red\]/';
$patterns[2] = '/\[blue\]/';
$patterns[3] = '/\[\/blue\]/';
$replacements = array();
$replacements[0] = '<span class="red">';
$replacements[1] = '</span>';
$replacements[2] = '<span class="blue">';
$replacements[3] = '</span>';
echo preg_replace($patterns, $replacements, $string);
// outputs: I want a <span class="red">red</span> apple and a <span class="blue">blue</span> umbrella
?>

你甚至可以更进一步,以更一般的方式编写代码(支持更多颜色,即):

$string = 'I want a [red]red[/red] apple and a [blue]blue[/blue] umbrella';
$regex = '/\[(red|green|blue)\]([^][]+)\[\/\1\]/i';
// provide an alternative and capture it in the first group
echo preg_replace($regex, "<span class='$1'>$2</span>", $string);

查看示例here