Search code examples
phpregexpreg-replacepreg-replace-callback

Php replace * with <b> tags


I want to replace *asd* with <b>asd</b> in my string.

*Abdāl* (*lit*: substitutes, but which can also mean generous [*karīm*]

In the above string, I want to replace *abdal* with <b>abdal</b> and also the other words that are enclosed with *.

How can I do this?

Mycode:

$s="*Abdāl* (*lit*: substitutes, but which can also mean generous [*karīm*]";
preg_replace_callback("#\*[^\*]*\*#",function ($string) { $string = preg_replace("/<a\s(.+?)>(.+?)<\/a>/is", "<b>$2</b>", $string); }, $s);

I am able to get the *abdal* string as matches inside the preg_replace_callback but now am trying to replace *abdal* to <b>abdal</b>.


Solution

  • You may use a simple call to preg_replace and use a regex with a capturing group over the value inside asterisks and a string replacement pattern with a placeholder to group 1:

    $s = "*Abdāl* (*lit*: substitutes, but which can also mean generous [*karīm*]";
    $s = preg_replace("#\*([^*]+)\*#", "<b>$1</b>", $s);
    echo $s; // => <b>Abdāl</b> (<b>lit</b>: substitutes, but which can also mean generous [<b>karīm</b>]  
    

    See the PHP demo.

    The regex is \*([^*]+)\* and it matches *, then matches and captures into Group 1 any one or more chars other than * (with [^*]+ - note the * does not have to be escaped inside the character class, and if you need to also process empty ** pairs, replace + with your * quantifier), and then matches a trailing *. The replacement pattern contains $1 that references the text stored in Group 1.

    See the regex demo.