1

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.

Jiminy Cricket
  • 908
  • 1
  • 9
  • 24
  • You're missing delimiters, and lenience for HTML weirdness (`




    ...`), and the Accept button on your previous questions.
    – Niet the Dark Absol Nov 16 '11 at 01:15
  • The "weird characters" is [Regular Expression](http://en.wikipedia.org/wiki/Regular_expression) syntax. – Zeenobit Nov 16 '11 at 01:17
  • You can learn about regular expressions (which is what you need for `preg_replace`) on http://regular-expression.info/ and the manual http://www.php.net/manual/en/reference.pcre.pattern.syntax.php of course. – mario Nov 16 '11 at 01:17
  • possible duplicate of [replace
    to new line between pre tag](http://stackoverflow.com/questions/3028322/replace-br-to-new-line-between-pre-tag) (Remember: You can always find a better answer if you try the search function yourself!)
    – mario Nov 16 '11 at 01:18

2 Answers2

6

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);
andrewtweber
  • 24,520
  • 22
  • 88
  • 110
2

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

michaeljdennis
  • 602
  • 1
  • 7
  • 12