using preg_replace to replace a <br />

烂漫一生 提交于 2020-01-05 03:57:09

问题


I've read a few articles on preg_replace and still don't understand what all the weird ]{!('/)[ characters mean.

Basically, I want to find the first instance of a break <br />, and replace it with a </strong><br />

Code I have: preg_replace('<br />', '</strong><br />', nl2br($row['n_message']), 1)

but I know I'm missing something in how I declare the strings <br /> and </strong>.

Any help? Thanks.


回答1:


Regular Expressions

The only thing you are missing is a delimiter in your regexp pattern. I believe this can be any character; a common choice is a forward slash. But then of course you must escape your existing forward slashes. Here are two examples, using forward slash and right square bracket.

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

Alternative

I agree with michaeljdennis that you should use str_replace in this case. preg_replace is appropriate for fancy replacements, but not one as simple as this.

However, str_replace does not have a $limit argument. If you wish to limit the number of replacements to the first instance, do something like

// 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);



回答2:


The weird characters you're referring to are regular expression patterns I assume.



来源:https://stackoverflow.com/questions/8145416/using-preg-replace-to-replace-a-br

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!