使用preg_replace替换<br/>

时间:2011-11-16 01:12:42

标签: php preg-replace

我已经阅读了一些关于preg_replace的文章,但仍然不明白所有奇怪的事情{!('/)[字符的意思。

基本上,我想找到休息<br />的第一个实例,并将其替换为</strong><br />

我的代码:preg_replace('<br />', '</strong><br />', nl2br($row['n_message']), 1)

但我知道我在如何声明字符串<br /></strong>时遗漏了一些内容。

有任何帮助吗?感谢。

2 个答案:

答案 0 :(得分:6)

正则表达式

您唯一缺少的是正则表达式模式中的分隔符。我相信这可以是任何角色;一个常见的选择是正斜杠。但当然,你必须逃避现有的正斜杠。以下是两个示例,使用正斜杠和右方括号。

$text = preg_replace('/<br \/>/', '</strong><br />', nl2br($text), 1);
$text = preg_replace(']<br />]', '</strong><br />', nl2br($text), 1);

<强>替代

我同意michaeljdennis的观点,在这种情况下你应该使用str_replacepreg_replace适合花哨的替换,但不适合这样简单。

但是,str_replace 具有$ limit参数。如果您希望限制第一个实例的替换次数,请执行类似

的操作
// Split the string into two pieces, before and after the first <br />
$str_parts = explode('<br />', $row['message'], 2);

// Append the closing strong tag to the first piece
$str_parts[0] .= '</strong>';

// Glue the pieces back together with the <br /> tag
$row['message'] = implode('<br />', $str_parts);

答案 1 :(得分:2)

您所指的奇怪字符是我假设的正则表达式。