str_replace不会替换阿拉伯字符

时间:2012-11-30 13:06:16

标签: php

<?php 
$utf8_string = 'مع السلامة مع السلامة مع السلامة مع السلامة مع السلامة مع السلامة مع السلامة السلامة الرائعة على الطويلة ';
echo $utf8_string;
echo'<br/><br/>';

$patterns = array("على", "مع");
$replacements   = array("", "");

$r_string = str_replace($patterns, $replacements, $utf8_string);

//echo $r_string;
print_r ($r_string);
echo'<br/>';
//$words = preg_split( "/ ( |مع|على) /",$r_string);
$words = explode(" ",$r_string);

$num = count($words);
echo 'There are <strong>'.$num.'</strong> words.';
?>

我有这个代码来计算阿拉伯语句子中的单词数量。但是我想删除一些单词并计算rest.i试图使用str_replace,但这种方式是计算原始句子的单词数。 有谁可以帮助我?

3 个答案:

答案 0 :(得分:4)

您可以使用:

$num = count(
    explode(
        " ", 
        str_replace(
            $word, //Word you want to remove from your text.
            "",
            $string //String you want the word to be removed from.
        )
    )
);

甚至:

$num = count(
    explode(
        " ", 
        str_replace(
            array("word1", "word2", [...]), //Words you want to remove from your text.
            "",
            $string //String you want the word to be removed from.
        )
    )
);

编辑:正如所指出的,上述情况不会奏效。我尝试查明错误的位置,显然 str_replace无法处理阿拉伯字符,即使explode可以。 PHP is not reliable with non-ascii characters.

您可以做的是:

$num = Count(explode(" ", $utf8_string)) - Count(array_intersect(explode(" ", $utf8_string), $patterns))

它应该返回你想要的值。

您也可以尝试编写自己的字符串替换函数,但我会反对它,看到您必须手动循环遍历数组并比较每个单词。这样做应该花费更长的时间来运行,并使其更加冗长。


来到这里警告你,处理这个问题的正确方法是使用mbstring扩展名(http://php.net/manual/en/book.mbstring.php)。请使用此扩展程序,不要使用上面的丑陋黑客/解决方法。

答案 1 :(得分:1)

删除一些单词之后,在使用explode计算空格之前,您需要“删除重复空格”。字符串前端和末尾的空格需要修剪(或类似的正则表达式)

    $r_string = trim(preg_replace('/\s+/u',' ',$r_string));

答案 2 :(得分:0)

使用$num = str_word_count($r_string);

而不是$num = count($words);

相关问题