使用preg_replace替换<br />

Jim*_*ket 1 php preg-replace

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

基本上,我想找到一个中断的第一个实例<br />,并用一个替换它</strong><br />

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

但我知道我错过在我如何声明字符串的东西<br /></strong>.

有帮助吗?谢谢.

and*_*ber 6

常用表达

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

$text = preg_replace('/<br \/>/', '</strong><br />', nl2br($text), 1);
$text = preg_replace(']<br />]', '</strong><br />', nl2br($text), 1);
Run Code Online (Sandbox Code Playgroud)

替代

我同意michaeljdennis你应该str_replace在这种情况下使用.preg_replace适合花哨的替代品,但不适合这样简单.

但是,str_replace不能有$限制的说法.如果您希望限制第一个实例的替换次数,请执行类似的操作

// 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);
Run Code Online (Sandbox Code Playgroud)