问题
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