【发布时间】:2020-11-01 03:34:53
【问题描述】:
我正在开发一个搜索引擎。我在网上找到了一个编写良好的 php 函数,可以从文本中列出关键字。该功能在英语中完美运行。然而,当我尝试用法语调整它时,我发现数组输出中没有显示“é”、“è”、“à”字母和所有带重音符号的字母。
例如,如果文本包含:“Hello Héllo” =>=> 输出 = "Hello Hllo"
我猜问题出在以下代码行中:
$text = preg_replace('/[^a-zA-Z0-9 -.]/', '', $text); // only take alphanumerical characters, but keep the spaces and dashes too…
有什么想法吗?非常感谢来自法国!
完整代码如下:
function generateKeywordsFromText($text){
// List of words NOT to be included in keywords
$stopWords = array('à','à demi','à peine','à peu près','absolument','actuellement','ainsi');
$text = preg_replace('/\s\s+/i', '', $text); // replace multiple spaces etc. in the text
$text = trim($text); // trim any extra spaces at start or end of the text
$text = preg_replace('/[^a-zA-Z0-9 -.]/', '', $text); // only take alphanumerical characters, but keep the spaces and dashes too…
$text = strtolower($text); // Make the text lowercase so that output is in lowercase and whole operation is case in sensitive.
// Find all words
preg_match_all('/\b.*?\b/i', $text, $allTheWords);
$allTheWords = $allTheWords[0];
//Now loop through the whole list and remove smaller or empty words
foreach ( $allTheWords as $key=>$item )
{
if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) {
unset($allTheWords[$key]);
}
}
// Create array that will later have its index as keyword and value as keyword count.
$wordCountArr = array();
// Now populate this array with keywrds and the occurance count
if ( is_array($allTheWords) ) {
foreach ( $allTheWords as $key => $val ) {
$val = strtolower($val);
if ( isset($wordCountArr[$val]) ) {
$wordCountArr[$val]++;
} else {
$wordCountArr[$val] = 1;
}
}
}
// Sort array by the number of repetitions
arsort($wordCountArr);
//Keep first 10 keywords, throw other keywords
$wordCountArr = array_slice($wordCountArr, 0, 50);
// Now generate comma separated list from the array
$words="";
foreach ($wordCountArr as $key=>$value)
$words .= " " . $key ;
// Trim list of comma separated keyword list and return the list
return trim($words," ");
}
echo $contentkeywords = generateKeywordsFromText("Hello, Héllo");
【问题讨论】:
-
你可能想要
preg_replace('/[^\p{L}0-9 .-]+/u', '', $text) -
@WiktorStribiżew 这个函数 [preg_replace('/[^\p{L}0-9 .-]+/u', '', $text)] 只删除“é”。输出=“你好”。问题仍未解决。还有其他想法吗?
-
好吧,似乎该函数在此 preg_replace 某处停用...请参阅代码 [链接] (3v4l.org/YYHVB)
-
用
/\b.*?\b/i查找所有单词是一件非常奇特的事情,我以前从未见过这个:) 你只需要preg_match_all('/\w+/u', $text, $allTheWords);。您还可以修复空格缩小$text = preg_replace('/\s{2,}/ui', '', $text);。见this PHP demo。
标签: php preg-replace keyword diacritics