using preg_replace to replace a

2019-08-10 09:42发布

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.

2条回答
爷的心禁止访问
2楼-- · 2019-08-10 09:50

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

查看更多
欢心
3楼-- · 2019-08-10 10:17

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);
查看更多
登录 后发表回答