我正在尝试将字符串中的所有单词提取到数组中,但是我遇到了一些空格问题(& nbsp;).
这就是我做的:
//Clean data to text only
$data = strip_tags($data);
$data = htmlentities($data, ENT_QUOTES, 'UTF-8');
$data = html_entity_decode($data, ENT_QUOTES, 'UTF-8');
$data = htmlspecialchars_decode($data);
$data = mb_strtolower($data, 'UTF-8');
//Clean up text from special chrs I don't want as words
$data = str_replace(',', '', $data);
$data = str_replace('.', '', $data);
$data = str_replace(':', '', $data);
$data = str_replace(';', '', $data);
$data = str_replace('*', '', $data);
$data = str_replace('?', '', $data);
$data = str_replace('!', '', $data);
$data = str_replace('-', ' ', $data);
$data = str_replace("\n", ' ', $data);
$data = str_replace("\r", ' ', $data);
$data = str_replace("\t", ' ', $data);
$data = str_replace("\0", ' ', $data);
$data = str_replace("\x0B", ' ', $data);
$data = str_replace(" ", ' ', $data);
//Clean up duplicated spaces
do {
$data = str_replace(' ', ' ', $data);
} while(strpos($data, ' ') !== false);
//Make array
$clean_data = explode(' ', $data);
echo "<pre>";
var_dump($clean_data);
echo "</pre>";
这输出:
array(58) {
[0]=>
string(5) " "
[1]=>
string(5) " "
[2]=>
string(11) "anläggning"
[3]=>
string(3) "med"
[4]=>
string(3) "den"
[5]=>
string(10) "erfarenhet"
[6]=>
string(3) "som"
}
如果我检查输出的源,我看到前两个数组值是& nbsp;.
无论我如何尝试,我都无法从字符串中删除它.有任何想法吗?
array(56) {
[0]=>
string(1) "�" //Notice change. Instead of string length 5 it Now says 1. But still its garbage.
[1]=>
string(1) "�"
[2]=>
string(11) "anläggning"
[3]=>
string(3) "med"
[4]=>
string(3) "den"
[5]=>
string(10) "erfarenhet"
[6]=>
string(3) "som"
[7]=>
string(5) "finns"
[8]=>
string(4) "inom"
谢谢!
答案(对于懒人):
即使你对这个问题的解决方法略有不同,但它从来没有真正解答为什么我遇到了上面遇到的问题(比如剩下的和其他奇怪的空间),我喜欢它,它比我的好多了原始代码.
感谢所有为此做出贡献的人!
//Clean data to text only
$data = strip_tags($data);
$data = html_entity_decode($data, ENT_QUOTES, 'UTF-8');
$data = htmlspecialchars_decode($data);
$data = mb_strtolower($data, 'UTF-8');
//Clean up text from special chrs
$data = str_replace(array("-"), ' ', $data);
$clean_data = str_word_count($data, 1, 'äöå');
echo "<pre>";
var_dump($clean_data);
echo "</pre>";
解决方法:
好的,你唯一要做的就是更换& nbsp;您已经使用空格(仅当字符串确实包含& nbsp;检查@Andy E’s answer以确保您的数据不包含任何HTML实体时).:
$data = str_replace(" ", ' ', $data);
然后你可以用str_word_count
得到这些词:
$words = str_word_count($data, 1, 'äöåÄÖÅ');
P.S.:首先调用htmlentities然后用html_entity_decode再次恢复它的意义是什么?
更新:示例:
$str = ' anläggning med den erfahrenhet som åååÅ ÅÅ';
print_r(str_word_count($str, 1, 'äöåÄÖÅ'));
版画
Array
(
[0] => anläggning
[1] => med
[2] => den
[3] => erfahrenhet
[4] => som
[5] => åååÅ
[6] => ÅÅ
)
阅读文档有帮助:)