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

答案:

答案1:

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

<?php

$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
1  
Thanks man for pointing me in the rite direction, this worked preg_replace("/([^'])'([^']+)'([^'])/", '$1[$2]$3', $string);
– Sboniso Marcus Nzimande
2 hours ago

原文地址:

https://stackoverflow.com/questions/47750632/how-do-i-replace-quotes-with-square-brackets-in-a-string

Tags:,

添加评论

友情链接:蝴蝶教程