【问题标题】:remove special characters in php去除php中的特殊字符
【发布时间】:2014-03-27 18:18:28
【问题描述】:

我有许多带有特殊字符的描述,例如 é、ô 等等,并尝试使用以下命令删除它们:

$string = str_replace("é", " ", $string)
$string = ereg_replace("é", " ", $string)
$string = mysql_real_escape_string($string)

但没有任何作用,特殊字符仍然存在,并且描述未插入数据库中。我无法删除所有特殊字符,因为在描述中有需要的 html 标记。

感谢您的帮助!

【问题讨论】:

  • 一切都是 UTF8 吗?听起来您有多种字符集。
  • 我得到的数据库表行设置为utf8_bin

标签: php mysql special-characters


【解决方案1】:

简单易懂:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

用法:

echo clean('a|"bc!@£de^&$f g');

将输出:abcdef-g

编辑

Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1? Thanks in advance!

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

refer this link

【讨论】:

  • 等一下我可以试试
  • 它删除了所有 html 开头的结束标记符号,我注释掉删除空格的部分,因为我需要它们,我需要像 () 这样的字符
  • preg_replace('/[^A-Za-z0-9\-()<>= "\/]/', '', $string) 试过了,现在html标签看起来没问题,并删除了特殊字符,坦克寻求帮助
【解决方案2】:

http://www.php.net/manual/en/function.str-replace.php

这个函数返回一个字符串或一个数组,替换后的值。

你需要使用返回值

$string = str_replace("é", " ", $string);

【讨论】:

  • 对不起,我知道,你忘了写在我的问题中。
【解决方案3】:

使用character transliteration

例子:

<?php
$string = "ʿABBĀSĀBĀD";

echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
// output: ABBASABAD

?>

【讨论】:

    【解决方案4】:
    mysql_real_escape_string(htmlentities($string));
    

    【讨论】:

    • 返回一个长度为0的字符串
    • 你有数据库连接吗???来自手册: MySQL 连接。如果未指定链接标识符,则假定由 mysql_connect() 打开的最后一个链接。如果没有找到这样的链接,它将尝试创建一个,就好像 mysql_connect() 没有参数被调用一样。如果未找到或建立连接,则会生成 E_WARNING 级别错误。
    猜你喜欢
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多