加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 无法使用str_replace删除特殊字符

发布时间:2020-12-13 22:12:45 所属栏目:PHP教程 来源:网络整理
导读:我对str_replace有一个非常微不足道的问题. 我有一个带有En Dash字符的字符串( – ),如下所示: I want to remove - the dash html输出是 I want to remove the ndash; the dash 我想做这个: $new_string = str_replace ('-','',$string); 我试图用html_ent
我对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删除,但没有任何结果.

我做错了什么?

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

$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上运行,而charset是UTF-8,对于DB整理来说也是如此.

解决方法

尝试这样的事情:

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 6F(Hello).检查看两个情况下的短划线实际上是相同的字符.如果你看到“2D”在哪里短划线,这是一个字面减号……如果你看到三字节序列E2 80 93,那就是& ndash;.其他任何意味着不同的字符……

编辑:如果你看到26 6E 64 61 73 68 3B,那么你需要做str_replace(‘& ndash;’,”,$str);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读