1
$remarks = preg_replace('/'.$searchText.'/i', '<span class="searchText">$0</span>', $remarks);

I use the line of code above to highlight the search text that has been entered by the user. It works 99% of the time except when the search string happens to contain a forward slash (/) character. When they do that, php returns a "unknown modifier" error. I've tried escaping the forward slash with a back slash character by adding this line of code ahead of the preg_replace line.

$searchText = str_replace('/', '\/', $searchText);

That doesn't seem to help. How do I make this work?

3
  • Any reason you're using str_replace instead of preg_replace in your additional line to remove any additional slashes? With the additional line also, have you tried replacing the / with nothing rather than escaping it? Commented Dec 8, 2011 at 13:32
  • possible duplicate of preg_replace error Commented Dec 8, 2011 at 13:36
  • I used str_replace instead of preg_replace because I don't think I need the extra capabilities of preg_replace. If I replace the / with nothing, then it won't highlight the proper text. Commented Dec 8, 2011 at 14:49

1 Answer 1

2

That's what preg_quote is for:

$searchText = preg_quote($searchText, '/');
preg_replace("/$searchText/i", ...)
Sign up to request clarification or add additional context in comments.

1 Comment

After I add that line I get a "Compilation failed: regular expression too large at offset 0" error.

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.