Jump to content

problem with variable and strtr function


JimInWOodstock

Recommended Posts

I have been using PHP for years and consider myself fairly proficient. However, I am baffled by the following code.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?php
/* this code tries to translate the "right" single quote and "left" single quote to regular quote. Same with the right and left double quotes.
   Change them to regular double quotes.
*/
$message = '‘single quoted string’ “double quoted string”';
$from = '‘’“”';
echo '<h4>';
echo 'from = ' . $from . '<br>';
echo 'from length = ' . strlen($from) . '<br>';	// length should be 4; displays 12
$from = '‘' . '’' . '“' . '”';
echo 'from = ' . $from . '<br>';
echo 'from length = ' . strlen($from) . '<br>';	// length should be 4; displays 12
$to = "'" . "'" . '"' . '"';
echo 'to = ' . $to . '<br>';
echo 'to length = ' . strlen($to) . '<br>';		// length shows 4; this is correct
echo 'Original text = ' . $message . '<br>';
$message1 = strtr($message, $from, $to);
echo 'Translated text = ' . $message1 . '<br>';	// translated text is not correct
echo '</h4>'
?>
</body>
</html>

 

Run this code and the output is not even close to what I want. Any help would be greatly appreciated.

 

 

preg_replace would change the characters easily. Is that all you want to do?

 

$message = '‘single quoted string’ “double quoted string”';
$patterns[0] = '/(‘|’)/';
$patterns[1] = '/(“|”)/';
$replacements[0] = "'";
$replacements[1] = '"';
$message1 = preg_replace($patterns,$replacements,$message);
echo 'Translated text = ' . $message1 . '<br>';

The "smart quotes" are part of the ascii set. Their values are 0x91, 0x92, 0x93, and 0x94.

 

The preg_replace code works great and I have added it into my actual code. However I find it interesting that the strlen is wrong and apparently, that causes the strtr to fail. If anyone knows why the strlen of the 4 chars shows as 12, I would be very interested.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.