mario
mario

Reputation: 624

preg_replace, unable to insert '\' '

I would like to define something like:

preg_replace('é','\\\'{e}', 
    preg_replace('à','\\`{a}',
    preg_replace('è','\\`{e}',
    preg_replace('ì','\\`{i}', 
    preg_replace('ò','\\`{o}', 
    preg_replace('ù','\\`{u}',$text))))))

I am trying to substitute

è --> \'{e}
à --> \`{a} and so on

I always get

Warning: preg_replace(): No ending delimiter '�' found in /var/www/html/..../ on line 22 

Upvotes: 0

Views: 54

Answers (2)

revo
revo

Reputation: 48711

I suggest to not use preg_replace here, no need for regular expressions as there's a better way:

$find = array('é', 'à', 'è', 'ì', 'ò', 'ù');
$repl = array("\\'{e}", "\\`{a}", "\\`{e}", "\\`{i}", "\\`{o}", "\\`{u}");
$text = str_replace($find, $repl, $text);

But as your question, you made wrong nested preg_replace in addition to not having defined a delimiter. You can achieve what you need with working by preg_replace_callback as I noticed you want single quote for some accented characters and acute for the other ones:

Update #1: Using preg_replace_callback

$text = preg_replace_callback(
    '@é|à|è|ì|ò|ù@',
    function ($match)
    {
        return ($match[0] == 'é') ? "\\'é" : "\\`$match[0]";
    },
    $text
 );

Upvotes: 1

fnightangel
fnightangel

Reputation: 426

You're missing / in the pattern. Try this way:

preg_replace('/é/','\\\'{e}', 
preg_replace('/à/','\\`{a}', 
preg_replace('/è/','\\`{e}', 
preg_replace('/ì/','\\`{i}', 
preg_replace('/ò/','\\`{o}', 
preg_replace('/ù/','\\`{u}',$text))))))

Upvotes: 1

Related Questions