带字符串的preg_replace()包含" *"字符

时间:2014-08-20 02:39:34

标签: php preg-replace

我制作了一个脚本来突出显示字符串中的单词。脚本如下。

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);

运行脚本时,出现以下错误:

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

任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:4)

这可以帮到你:

<?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);

答案 1 :(得分:1)

"*"更改为"\*"并获利。

答案 2 :(得分:1)

您可以检查功能highlight_text

中是否有特殊字符

像:

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;
}

答案 3 :(得分:1)

将您的代码更改为

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);

然后就可以了。