无法使用str_replace删除特殊字符

时间:2010-07-02 18:55:49

标签: php str-replace html-encode

我对str_replace有一个非常微不足道的问题。

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

I want to remove - the dash

html输出

I want to remove the – the dash

我想这样做:

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

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

我做错了什么?

CNC中 这是我的脚本的完整代码:

$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);

没有人工作。 基本上问题是在DB中,破折号存储为“减号”(我用减号键输入值),但由于一个奇怪的原因,输出是& ndash;

我在Wordpress上运行,而字符集是UTF-8,对于数据库整理也是如此。

8 个答案:

答案 0 :(得分:9)

尝试这样的事情:

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

我的猜测是它不是真正的ndash,而是一个非常相似的角色。我建议拉出字符串中每个字符的字节值,看看它是什么样的:

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 6FHello)。检查两种情况下的破折号实际上是相同的字符。如果你看到破折号所在的“2D”,那就是一个字面减号...如果你看到三个字节序列E2 80 93,那就是&ndash;。其他任何意味着不同的字符...

修改 如果您看到26 6E 64 61 73 68 3B该文字是文字&ndash;,那么您需要str_replace('&ndash;', '', $str);

答案 1 :(得分:3)

我设法通过调用functions.php中的remove_filter( 'the_title', 'wptexturize' );来执行此操作,然后执行str_replace或其他任何“ - ”符号;

答案 2 :(得分:1)

&ndash;( - )并且减去符号( - )。确保你没有尝试更换错误的角色。

答案 3 :(得分:1)

我尝试了一切,没有任何效果。但最后在http://www.ascii.cl/htmlcodes.htm

的帮助下

这段代码对我有用

        $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);

答案 4 :(得分:0)

试试这个:

$new_string = str_replace('&ndash;','',$string);

或者:

$new_string = str_replace(html_entity_decode('&ndash;'),'',$string);

基本相同:

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

答案 5 :(得分:0)

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

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

答案 6 :(得分:0)

只有这个解决方案对我有用:

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

答案 7 :(得分:0)

对于那些尝试了以上所有但仍然没有快乐的人来说,这对我有用(来自WordPress $new_string = str_replace('&#8211;', 'or', $string); 功能)

var hash = await client.SendCodeRequestAsync(NotRegisteredNumberToSignUp);
var code = Console.ReadLine(); //Input the code, that was sent to your phone
var loggedInUser = await client.MakeAuthAsync(NotRegisteredNumberToSignUp, hash, code);