replace asterisk (*) with label b as appropriate

0

I have the following example text:

Hola bienvenido ah *tu sitio.com*

para continuar oprime *cualquier tecla*

What I need is to change the asterisks for the <b> tag in php but it would be relatively, if you already opened a tag to close it, it should look like this:

Hola bienvenido ah <b>tu sitio.com</b>

para continuar oprime <b>cualquier tecla</b>

I have the following code for now, but I can not do it:

$partsBlod = explode('*',$value->txt_msn);  
   if (count($partsBlod)>1) {
       $textNew = "";
       for ($i=0; $i < count($partsBlod); $i++) { 
         if ($i == 0) {
            $textNew .= $partsBlod[$i] . '<b>';
         }else{
            $textNew .= $partsBlod[$i] . '</b><b>';
         }
   }
   $value->txt_msn = $textNew;
    
asked by Jhonatan Rodriguez 15.02.2018 в 00:00
source

2 answers

3

You can use the preg_replace_callback function, which we pass to you as parameters an expression regular, a function and the text we want to try. In the regular expression we will say that it matches everything that is within two * . In this way:

$texto = '
Hola bienvenido ah *tu sitio.com*

para continuar oprime *cualquier tecla*
';
$regex = '/\*(.*?)\*/s';

$texto = preg_replace_callback(
    $regex,
    function($matches) {
        return sprintf(
            '<b>%s</b>',
            $matches[1]
        );
    },
    $texto
);

echo '<pre>';
echo $texto;
echo '</pre>';

It will print this:

Hola bienvenido ah <b>tu sitio.com</b>

para continuar oprime <b>cualquier tecla</b>
    
answered by 15.02.2018 / 04:44
source
1

If you take an asterisk in any position, you just have to replace it with:

$resultado = preg_replace( '/\*([^*]+)\*/', '<b>$1</b>', $texto);


The regular expression matches

  • \* an asterisk
  • ([^*]+) group 1 (the parentheses capture the text)
    • [^*]+ one or more characters other than asterisks
  • \* the other asterisk

And, when replacing it with <b>$1</b> , $1 contains the text that coincided with group 1.


On the other hand, if you want to allow escape sequences such as \* in the text, so that the user can use an asterisk that does not mean bold, you have to use this regex:

/\*([^\*]*(?:\.[^\*]*)*)\*/
    
answered by 15.02.2018 в 15:47