too long

I have made a script to highlight a word in a string. The script is below.

function highlight_text($text, $words){
  $split_words = explode( " " , $words );
  foreach ($split_words as $word){
    $color = '#FFFF00';
    $text = preg_replace("|($word)|Ui", "<span style=\"background:".$color.";\">$1</span>", $text );
  }
  return $text;
}

$text = '*bc';
$words = '*';

echo highlight_text($text, $words);

When running the script, I got the following error:

Warning: preg_replace(): Compilation failed: nothing to repeat at offset 1

Can anyone help me?

change "*" to "\*" and profit.

You can check if special character in function highlight_text

like:

function highlight_text($text, $words){
  $split_words = explode( " " , $words );
  foreach ($split_words as $word){
    $str = '';
    $word = str_split($word);
    foreach ($word as $c) {
      if ($c == '*') {
        $str .= '\*';
      }
      else {
        $str .= $c;
      }
    }

    $color = '#FFFF00';
    $text = preg_replace("|($str)|Ui", "<span style=\"background:".$color.";\">$1</span>", $text );
  }
  return $text;
}

Change your code to

function highlight_text($text, $words){
    $split_words = explode( " " , $words );
    foreach ($split_words as $word){
        $color = '#FFFF00';
        $word = preg_quote($word, '/');
        $text = preg_replace("|$word|Ui", "<span style=\"background:".$color.";\">$0</span>", $text );
    }
    return $text;
}

$text = '*bc';
$words = '*';

echo highlight_text($text, $words);

then will be ok.

This can help you:

<?php
 function highlight_text($text, $words){
  $split_words = explode( " " , $words );
  foreach ($split_words as $key=>$word){
  if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $word))// looking for special characters
                 {
                    $word = preg_quote($word, '/');// if found output \ before that 
                          }
    $color = '#FFFF00';
    $text = preg_replace("|($word)|Ui", "<span style=\"background:".$color.";\">$1</span>", $text );
  }
  return $text;
}

$text = '*bc';
$words = '*';

echo highlight_text($text, $words);