Fernando Luiz
Fernando Luiz

Reputation: 131

How to replace double quotes?

I have a string: "Blah blah blah "blah" blah blah", and I need to replace quotes on this string to «Blah blah blah «blah» blah blah»

I was trying to use this script:

$m=preg_replace('/([^\s>])\\\"/s',"$1»",$m);
$m=preg_replace('/\\\"([^\s])/s',"«$1",$m);

But when the string beginning from the space, i have something like that:

 »Some text» Some text Some text

How can I do this?

Upvotes: 1

Views: 1077

Answers (3)

Code Magician
Code Magician

Reputation: 23972

The most direct approach might be to use lookarounds to detect it the quote is directly before a word or directly after.

$m = preg_replace('/"(?=\w)/', '«', $m);
$m = preg_replace('/(?<=\w)"/', '»', $m);

This will work well on your example, but may be too simplistic. You might want to go further and look for a word charactor or punctuation so "blah blah." will match as well. That would make the second example something like this: /(?<=[\w,.?!\)])"/

Upvotes: 2

Empty
Empty

Reputation: 457

$str = '"Test string "blabla" sdf "dd" dffdsf"';
$result = preg_replace('/(\s)"([^"]+)"(\s)/', '$1«$2»$3', $str);
$result = preg_replace('/^"(.*?)"$/', '«$1»', $result); // replace first and last quotes

This code works only for strings without many nested quotes. This code don't work for string:

"Test "string is "test" test" test"

Upvotes: 0

Ruslan F.
Ruslan F.

Reputation: 5776

may be such way ?

$m=str_replace("&lt;","",$m); 
$m=str_replace("&rt;","",$m);

Upvotes: -1

Related Questions