PHP/Regex replace inch character with proper quotation marks

Viewed 143

I want to replace inch characters " with proper German quotation marks „example“.

An example String would be:

$string = `Mein Name ist "Joseph"`

I tried

str_replace("\"", '„', $string) 

but of course it's replacing all of the inch characters with the same quotation mark

Mein Name ist „Joseph„ 

So I guess I need a regex to somehow replace the inch character before a word with „ and the inch character after the same word with “ to get the result

Mein Name ist „Joseph“

Despite reading how regex works, I can't really figure out how to achieve that.

Any tips would be gladly welcomed, thx!

2 Answers

Try something like this,

$re = '/("([^"]*)")/';
$str = 'Mein Name ist "Joseph"';
$subst = '„$2“';

$result = preg_replace($re, $subst, $str);

echo $result;

Check out, preg_replace function

Made this on regex.com

Here you go. I used a regex to replace the first " and then replaced everything else with the second character.

$string = 'Mein Name ist "Joseph"';
$patterns = array();
$patterns[0] = '/ "/';
$patterns[1] = '/^"/';
$replacements = array();
$replacements[1] = ' „';
$replacements[0] = '^„';
$str = preg_replace($patterns, $replacements, $string);
$str = str_replace("\"", '“', $str);
echo $str;
Related