关于php:无法使用str_replace删除特殊字符

Can't remove special characters with str_replace

str_replace有一个非常琐碎的问题。

我有一个带有En Dash字符(-)的字符串,如下所示:

1
I want to remove - the dash

html输出为

1
I want to remove the  the dash

我想这样做:

1
$new_string = str_replace ('-','',$string);

我尝试使用html_entity_decode解析字符串,使用htmlspecialchars解析要删除的字符,但没有任何结果。

我做错了什么?

-编辑-
这是我的脚本的完整代码:

1
2
3
4
5
$title = 'Super Mario Galaxy 2 - Debut Trailer'; // Fetched from the DB, in the DB the character is - (minus) not

$new_title = str_replace(' - ', '', $title);
$new_title = str_replace(" -", '', $title);
$new_title = str_replace(html_entity_decode(''),'',$title);

没有人起作用。
基本上问题是在数据库中,破折号存储为" minus "(我用减号键输入值),但是由于一个奇怪的原因,输出是


尝试类似这样的内容:

1
str_replace(html_entity_decode('', ENT_COMPAT, 'UTF-8'), '', $string);

我的猜测是,这实际上不是ndash,而是一个非常相似的角色。我建议拉出字符串中每个字符的字节值以查看其外观:

1
2
3
4
5
6
7
8
9
10
11
12
13
function decodeString($str) {
    //Fix for mb overloading strlen option
    if (function_exists('mb_strlen')) {
        $len = mb_strlen($str, '8bit');
    } else {
        $len = strlen($str);
    }
    $ret = '';
    for ($i = 0; $i < $len; $i++) {
        $ret .= dechex(ord($str[$i])).' ';
    }
    return trim($ret);
}

这会将字符串转换为单独的字节编码(将其转换为十六进制字符串,例如48 65 6C 6C 6F(Hello)。检查两种情况下的破折号实际上是相同的字符。如果看到" 2D",其中的破折号是文字减号...如果看到三个字节序列E2 80 93,则是。其他任何内容都表示不同的字符...

编辑:
而且,如果您看到26 6E 64 61 73 68 3B表示文字,那么您就需要执行str_replace('', '', $str);


我已经设法通过在functions.php中调用remove_filter( 'the_title', 'wptexturize' );来做到这一点,然后执行str_replace或任何带有"-"符号的内容;


我尝试了一切,但无济于事。但最后在http://www.ascii.cl/htmlcodes.htm

的帮助下

此代码确实对我有用

1
2
3
4
5
6
7
8
9
10
11
12
        $arr1 = explode(",","0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F");
        $arr2 = explode(",","B,C,D,E,F");

        foreach($arr2 as $t1){
            foreach($arr1 as $t2){
                $val = $t1.$t2;
                $desc = str_replace(chr(hexdec($val)),"",$desc);
            }  
        }

        // if need removing individual value
        $desc = str_replace(chr(hexdec('A2')),"",$desc);

有一个(a€")和一个减号(-)。确保您没有尝试替换错误的字符。


对于尝试过上述所有方法但仍然不满意的任何人,这对我来说是有效的(通过WordPress get_the_title()函数)

1
$new_string = str_replace('', 'or', $string);


仅此解决方案对我有用:

1
$string = str_replace("\\x96","-", $string);

这是我解决无效ndash的方法:

1
$string = str_replace(chr(hexdec('3f')), '-', $string);

尝试一下:

1
$new_string = str_replace('','',$string);

或:

1
$new_string = str_replace(html_entity_decode(''),'',$string);

基本上与以下内容相同:

1
$new_string = str_replace ('-','',$string);