3

Hello Stackers,

I'm just having a small PHP Question about the str_replace() Function. When I replace something, it will just replace everything; That's okay. But what I would like to know is this:

str_replace("*", "<strong>", $message);

Is it possible to use str_replace for codes like * This content is Bold *, just having the content, but still replacing the asterisk's with <strong> and </strong>?

Example:

Original: **This Should be Bold** After Replacing: <strong>This Should be Bold</strong>

For people flagging this as a Duplicate: It's not about closing HTML Tags, it's about replacing.

I Hope I'm not that unclear. Thanks.

7
  • Take a look at preg_replace()
    – Rizier123
    Feb 15, 2016 at 13:04
  • Not with str_replace, you can do it with PREG_REPLACE Feb 15, 2016 at 13:04
  • 3
    There are already libraries that can do that for you, just look for something like php markdown.
    – jeroen
    Feb 15, 2016 at 13:08
  • 3
    Do you want to write a markdown parser? If so, I recommend to use an existing library instead of writing your own (unless you want to practice how to write and optimize parsers)
    – Pred
    Feb 15, 2016 at 13:08
  • 1
    @jeroen that's the most sensible suggestion, I second that Feb 15, 2016 at 13:10

2 Answers 2

3

Use regular expression instead; it's more convenient:

$message = "**This Should be Bold**";
$message = preg_replace('#\**([^\*]+)\**#m', '<strong>$1</strong>', $message);
echo $message;

Or if you want to limit the number of asteroids to 2:

'#\*{1,2}([^\*]+)\*{1,2}#m'
5
  • @Gouda Elalfy why did you change [^\*]+ to [^\**]+?
    – SOFe
    Feb 15, 2016 at 13:19
  • to replace 2 * stars Feb 15, 2016 at 13:20
  • @GoudaElalfy but inside []? Are you sure?
    – SOFe
    Feb 15, 2016 at 15:27
  • If you want to support **This bold has a * inside**, maybe you can try doing the replaces one by one.
    – SOFe
    Feb 15, 2016 at 15:29
  • @Phil_1984_ edited, thanks. But still, different for those inside []
    – SOFe
    Feb 15, 2016 at 18:29
1

You can also do like this

https://eval.in/518881

<?php
    $string = '**This Should be Bold**';
    $string = preg_replace("/\*\*(.+?)\*\*/", "<strong>$1</strong>", $string);
    echo $string;
?>
1
  • Will not work with **This** and **this** are both bold. The and will become bold too,
    – SOFe
    Feb 15, 2016 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.