Reputation:
I need to escape brackets within a file name. Currently I do this as follows:
$string = 'folder1/folder2/foldera/abc/myFile(2).jpg';
str_replace(')', '\)', str_replace('(', '\(', $string));
echo $string;
// outputs: folder1/folder2/foldera/abc/myFile\(2\).jpg
It is inefficient as this is executed within a loop of hundreds of results. Is there a better, cleaner more efficient way of achieving this?
Upvotes: 1
Views: 7762
Reputation: 3855
You can reduce one call to str_replace()
, by using array.
str_replace(array(')', '('), array('\)', '\('), $string);
P.S. : Another option would be preg_quote()
, but in your case you want to escape only (
and )
. And preg_quote()
will escape all regex
characters.
Upvotes: 3
Reputation: 4350
I wonder if a better function is escapeshellcmd
(http://php.net/manual/en/function.escapeshellcmd.php) which
Following characters are preceded by a backslash: &#;`|*?~<>^()[]{}$\, \x0A and \xFF. ' and " are escaped only if they are not paired. In Windows, all these characters plus % and ! are replaced by a space instead.
Upvotes: 0
Reputation: 709
Try this
$findstring = array('(',')');
$escpestring = array('\(','\)');
$string = 'folder1/folder2/foldera/abc/myFile(2).jpg';
$output = str_replace($findstring,$escpestring,$string);
echo $output;
Upvotes: 2
Reputation: 3031
I think you are looking for preg_quote :
$string = preg_quote($string);
or something more like :
$string = str_replace([')', '('], ['\\)', '\\('], $string);
Upvotes: 2