0
error:preg_match_all(): Compilation failed: nothing to repeat at offset 59

Hello everyone, I am trying to make a word filter for a client and i have ran into the issue that my code witch is pulling words from a text file can not read the $ character from my text file, mycode is below.

 $lines=array();
  $fp=fopen('/opt/lampp/htdocs/Comments/Classes/Bad.txt', 'r');
  while (!feof($fp))
  {
    $line=fgets($fp);
    //process line however you like
    $line=trim($line);
    //add to array
    $lines[] = preg_quote(trim($line));
  }
    fclose($fp);
    $string = Input::get('comments');
    $matches = array();
    $matchFound = preg_match_all(
      "/\b(" . implode("|", $lines) . ")\b/i", 
            $string, 
            $matches
          );
    if ($matchFound) {
      $this->addError("The following is not allowed please change it.");
      $words = array_unique($matches[0]);
      foreach($words as $word) {
        echo "<li>" . $word . "</li>";
      }
      echo "</ul>";
    }

2 Answers 2

2

Use preg_quote on each line while reading in the text file.

Sign up to request clarification or add additional context in comments.

Comments

0

You're probably inserting text that happen contains regex metacharacters, and inserting them in such a way that they're actually treated as metachars. You need to preg_quote() the text you're inserting to escape all of those metachars.

10 Comments

So it would would look something like this $line=trim(preg_quote($line));
don't manipulate the quoted string in any way once it's been quoted. trim() won't do much, but any other manipulations COULD undo the quoting. trim THEN quote.
I did the preg_quote after the then and it still isnt searching for the special character i may be doing something wrong i updated the code above
You've got preg_quote($lines), and $lines is your array. so you're using an array in string context, and PHP will politely convert that array into the literal word Array. try $lines[] = preg_quote(trim($line)).
So i echo the array and found that the line isn't $$ in the array it is \$\$ could that be because of my sanitize function htmlentities(string)($string, ENT_QUOTES, 'UTF-8');
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.