Reputation: 1395
$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?
Upvotes: 1
Views: 2826
Reputation: 522005
That's what preg_quote
is for:
$searchText = preg_quote($searchText, '/');
preg_replace("/$searchText/i", ...)
Upvotes: 2