How do I replace quotes with square brackets in a string


I have this string 'My String' with square brackets eg [My String].

At the moment I can only get the string like:

$re = '/'([^']+)'/';
$str = "'My String'";
preg_match($re, $str, $matches);

How can I get replace the qoutes using preg_replace()


Why not use preg_replace in the first place? Also, you should form string literals correctly.
The issue I have is how to use preg_replace in this case.
– Sboniso Marcus Nzimande
5 hours ago



You can use this code to replace ” with []:


$string = "blabla'My String'blabla";
echo preg_replace("/([^']*)'([^']+)'([^']*)/", '$1[$2]$3', $string);
// Output will be "blabla[My String]blabla"

preg_replace is a core php function that replace a pattern in a string


Thanks for the answer but it’s not working. Problem is I do not know how the string is formated. it can be 'blabla' bla 'b' bla so I need braket where the string has qoutes
– Sboniso Marcus Nzimande
5 hours ago
With this code 'blabla' bla 'b' bla will be transformed to [blabla] bla [b] bla . Can you give me the expected output?
This just ads the bracket on the first and last quote of the string
– Sboniso Marcus Nzimande
4 hours ago
i.e [blabla bla b] bl
– Sboniso Marcus Nzimande
3 hours ago
Thanks man for pointing me in the rite direction, this worked preg_replace("/([^'])'([^']+)'([^'])/", '$1[$2]$3', $string);
– Sboniso Marcus Nzimande
2 hours ago