Reputation: 1146
I use the following code for replacing matched words within a String:
for ($i=0; $i < count($terms); $i++) {
if ( $terms[$i] == '' || $terms[$i] == ' ' || strlen($terms[$i])==0 ) continue;
$searchingFor = "/" . $terms[$i] . "/i";
$replacePattern = "<strong>$0</strong>";
$result['titulo'] = preg_replace($searchingFor, $replacePattern, $result['title']);
}
echo $result['title'];
Where 'terms' is an Array from $_GET['terms'].
All works fine except when user input strings containing characters like slashes. It arise an exception in preg_replace.
How can i solve this issue?
Thanks.
Upvotes: 0
Views: 1732
Reputation: 74685
You may want to consider using str_ireplace
to do a case-insensitive replacement rather than regular expressions:
$terms = array('cat', 'hat');
$result['title'] = "the CAT in the hat";
foreach ($terms as $term) {
if (trim($term) === '') continue;
$result['title'] = str_ireplace($term, "<strong>$term</strong>", $result['title']);
}
echo $result['title'];
Output:
the cat in the hat
One potential disadvantage of this is that the case of the original text is lost, taking on the case of the term in the replacement array. If that's a problem, you can adapt your original approach but use preg_quote
to escape the characters in your input:
$terms = array('c\a/t', 'hat?');
$result['title'] = "the C\A/T in the hat?";
$terms = array_filter($terms, 'strlen'); // filter out empty values
$patterns = array_map(function($t) { return "/" . preg_quote($t, "/") . "/i"; }, $terms);
$result['title'] = preg_replace($patterns, "<strong>$0</strong>", $result['title']);
echo $result['title'];
Output:
the C\A/T in the hat?
Upvotes: 1
Reputation: 2035
Use preg_quote:
$searchingFor = "/" . preg_quote($terms[$i], "/") . "/i";
This function puts a backslash \
before all characters used in preg syntax (. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
) and also before all characters in the second argument, used here to escape your delimiter character /
.
Upvotes: 2