Hashibul hasan
Hashibul hasan

Reputation: 187

PHP Preg_replace() pattern not work

I wan to replace text using preg_replace.But my search string have a / so it makes problem.

How can I solve it?

$search='r/trtrt';
echo preg_replace('/\b'.addslashes($search).'\b/', 'ERTY', 'TG FRT');

I am getting error preg_replace(): Unknown modifier 'T'

Upvotes: 0

Views: 1156

Answers (3)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

Why not escape it the way it is meant to be done

$search='r/trtrt';
 echo preg_replace('/\b'.preg_quote($search, '/').'\b/', 'ERTY', 'TG FRT');

http://php.net/manual/en/function.preg-quote.php

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters

delimiter

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

Add slashes is not the function to use here. It provides no escaping for any of the special characters in Regx.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Using the proper functions promote readability of the code, if at some later point in time you or another coder see the ~ delimiter they may just think its part of a personal "style" or pay it little attention. However, seeing the input properly escaped will tell any experienced coder that the input could contain characters that conflict with regular expressions.

Personally, readability is at the top of my list whenever I write code. If you cant understand it at a glance, what good is it.

Upvotes: 1

antoni
antoni

Reputation: 5546

use ~ as delimiter:

$search='r/trtrt';
echo preg_replace('~\b'.addslashes($search).'\b~', 'ERTY', 'TG FRT');

I always use ~ as it is one of the least used char in a string but you can use any character you want and won't need to escape your regexp chars!

You don't need addslashes() in your case but if you have a more complex regexp and you want to escape chars you should use preg_quote($search).

Upvotes: 2

chris85
chris85

Reputation: 23892

Use a different delimiter and don't use addslashes, that is escaping non-regex special characters (or a mix of regex and non-regex characters, I'd say the majority of the time dont use addslashes).

$search='r/trtrt';
echo preg_replace('~\b'. $search.'\b~', 'ERTY', 'TG FRT');

You could use preg_quote as an alternative. Just changing the delimiter is the easiest solution though.

Upvotes: 4

Related Questions