我在php中有以下代码
$test = "\151\163\142\156";
echo utf8_decode($test);
var_dump($test);我得到了以下结果:
isbn
string(4) "isbn"我从一个具有\151\163\142\156文本的txt文件中获取一些文本
$all_text = file_get_contents('test.txt');
var_dump($all_text);结果:
string(16) "\151\163\142\156"我有以下问题:
编辑
(摘自评论)
我尝试了所有的一切,并编码,但没有任何效果。.txt文件中的文本是字符串(16),而不是字符串(4),因此我可以对其进行编码。txt文件是用Western (ISO 8859-1)编码从崇高中保存的。
发布于 2016-06-22 14:25:00
,这与UTF-8编码完全无关,完全忘记了这一部分.utf8_decode在您的代码中什么也不做。iconv是完全不相关的。
它与PHP文字解释有关。\... in "\151\163\142\156"是一个特殊的PHP文本转义序列:
\[0-7]{1,3}与正则表达式匹配的字符序列是八进制表示法中的一个字符,它无声地溢出以适应一个字节(例如"\400“=== "\000")。 http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
这很容易解释为什么它在用PHP文字编写时工作,而在从外部源读取时不工作(因为通过file_get_contents读取的外部文本不被解释为PHP代码)。只需做echo "\151\163\142\156",您就会看到"isbn“,而不需要任何其他转换。
要手动将字符串\151\163\142\156中的单个转义序列转换为它们的字符等效项(实际上:它们的字节等效项):
$string = '\151\163\142\156'; // note: single quotes cause no iterpretation
echo preg_replace_callback('/\\\\([0-7]{1,3})/', function ($m) {
return chr(octdec($m[1]));
}, $string)
// isbnstripcslashes碰巧包含了这个功能,但是它也做了很多可能不想要的事情。
相反的是:
$string = 'isbn';
preg_replace_callback('/./', function ($m) {
return '\\' . decoct(ord($m[0]));
}, $string)
// \151\163\142\156发布于 2016-06-21 21:51:47
尝试使用stripcslashes:
<?php
$test = "\151\163\142\156";
echo utf8_decode( $test ); // "isbn"
var_dump( $test );
echo "<br/><br/><br/>";
$all_text = file_get_contents( "test.txt" );
echo utf8_decode( $all_text ) . // "\151\163\142\156"
"<br/>" .
utf8_decode( stripcslashes( $all_text ) ); // "isbn"
var_dump( stripcslashes( $all_text ) );
?>使用此文件进行测试:
这是一些文本: 151\163\142\156 这是更多的短信!
接下来是如何将字符转换为代码:
<?php
$test = "isbn";
$coded = "";
for ( $i = 0; $i < strlen( $test ); $i++ ) // PROCESS EACH CHAR IN STRING.
$coded .= "\\" . decoct( ord( $test[ $i ] ) ); // CHAR CODE TO OCTAL.
echo $coded . // "\151\163\142\156"
"<br/>" .
stripcslashes( $coded ); // "isbn".
?>让我们用一个可以在任何地方调用的函数来使它更加通用:
<?php
function code_string ( $s )
{ $coded = "";
for ( $i = 0; $i < strlen( $s ); $i++ )
$coded .= "\\" . decoct( ord( $s[ $i ] ) );
return $coded;
}
$x = code_string( "isbn" );
echo $x . // "\151\163\142\156"
"<br/>" .
stripcslashes( $x ); // "isbn".
?>https://stackoverflow.com/questions/37953733
复制相似问题