在 PHP 中,處理字符串中的特殊字符時,可以使用以下方法:
$str = "This is a line with a special character: \n";
echo $str;
輸出:
This is a line with a special character:
$str = "This is a line with a special character: \"Hello\"";
echo $str;
輸出:
This is a line with a special character: "Hello"
$str = 'This is a line with a special character: \n';
echo $str;
輸出:
This is a line with a special character: \n
addslashes()
函數:該函數會在字符串中的特殊字符前添加反斜杠(\)。例如:$str = "This is a line with a special character: \n";
$escaped_str = addslashes($str);
echo $escaped_str;
輸出:
This is a line with a special character: \n
stripslashes()
函數:該函數可以刪除字符串中由 addslashes()
函數添加的反斜杠(\)。例如:$escaped_str = "This is a line with a special character: \\n";
$unescaped_str = stripslashes($escaped_str);
echo $unescaped_str;
輸出:
This is a line with a special character: \n
htmlspecialchars()
函數:該函數會將特殊字符轉換為 HTML 實體。例如:$str = "This is a line with a special character: <br>";
$html_str = htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
echo $html_str;
輸出:
This is a line with a special character: <br>
根據實際需求,可以選擇合適的方法來處理字符串中的特殊字符。