2012-11-30 85 views
3
<?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.'; 
?> 

我有这样的代码来算在阿拉伯语sentence.however我想删除一些词和计数rest.i试图用str_replace函数单词的数量,但这种方式是计算原始句子的词数。 任何人都可以帮助我吗?str_replace函数不会取代阿拉伯字符

回答

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)。请使用此扩展程序,不要使用上面的丑陋攻​​击/解决方法。

+0

它没有work.it没有给我的话的正确数量 –

+0

输出是什么?它是否包括所有的单词?有些数字既不是预期的结果,也不是单词总数(替换前)? –

+0

它计算第一句话中的单词数量,这是18.我得到的结果是10在删除单词 –

1

您需要在删除一些单词之后以及在用爆炸计数空格之前“删除重复的空格”。修剪(或类似的正则表达式),需要对前端和末端的字符串的空间

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

使用$num = str_word_count($r_string);

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

+0

str_word_count doesnt读阿拉伯文words.That是我意识到bcz我试了很多次,它没有工作 –