我有一段PHP代码如下:
$words = array(
'Artist' => '1',
'Tony' => '2',
'Scarface' => '3',
'Omar' => '4',
'Frank' => '5',
'Torrentino' => '6',
'Mel Gibson' => '7',
'Frank Sinatra' => '8',
'Shakes' => '9',
'William Shakespeare' => '10'
);
$text = "William Shakespeare is very famous in the world. An artist is a person engaged in one or more of any of a broad spectrum of activities related to creating art, practicing the arts, and/or demonstrating an art. Artist is a descriptive term applied to a person who engages in an activity deemed to be an art. Frank Sinatra was an American singer, actor, director, film producer, and conductor. Frank Sinatra was born on December 12, 1915, in Hoboken, New Jersey, the only child of Italian immigrants Natalina Garaventa and Antonino Martino Sinatra, and was raised Roman Catholic.";
$re = '/\b(?:' . join('|', array_map(function($keyword) {
return preg_quote($keyword, '/');
}, array_keys($words))) . ')\b/i';
preg_match_all($re, $text, $matches);
foreach ($matches[0] as $keyword) {
echo $keyword, " ", $words[$keyword], "\n";
}
代码返回以下内容:
William Shakespeare 10 artist Artist 1 Frank 5 Frank 5
该代码非常适合不回应莎士比亚中的'Shakes' => '9'
等部分关键字。但是,正如您所看到的,代码无法将'Frank Sinatra' => '8'
检测为Frank Sinatra was an American singer
中的关键字,artist
也没有任何值(即1
)。你可以帮我修改代码,以便在当前版本中回显William Shakespeare 10 artist 1 Artist 1 Frank 5 Frank 5 Frank Sinatra 8 Frank Sinatra 8
而不是William Shakespeare 10 artist Artist 1 Frank 5 Frank 5
。谢谢你的帮助。
答案 0 :(得分:2)
我设法取得了成果:
William Shakespeare 10艺术家1艺术家1 Frank Sinatra 8 Frank Sinatra 8
使用代码:
<?php
mb_internal_encoding('UTF-8');
$words = array(
'Artist' => '1',
'Tony' => '2',
'Scarface' => '3',
'Omar' => '4',
'Frank' => '5',
'Torrentino' => '6',
'Mel Gibson' => '7',
'Frank Sinatra' => '8',
'Shakes' => '9',
'William Shakespeare' => '10'
);
uksort($words, function ($a, $b) {
$as = mb_strlen($a);
$bs = mb_strlen($b);
if ($as > $bs) {
return -1;
}
else if ($bs > $as) {
return 1;
}
return 0;
});
$words_ci = array();
foreach ($words as $k => $v) {
$words_ci[mb_strtolower($k)] = $v;
}
$text = "William Shakespeare is very famous in the world. An artist is a person engaged in one or more of any of a broad spectrum of activities related to creating art, practicing the arts, and/or demonstrating an art. Artist is a descriptive term applied to a person who engages in an activity deemed to be an art. Frank Sinatra was an American singer, actor, director, film producer, and conductor. Frank Sinatra was born on December 12, 1915, in Hoboken, New Jersey, the only child of Italian immigrants Natalina Garaventa and Antonino Martino Sinatra, and was raised Roman Catholic.";
$re = '/\b(?:' . join('|', array_map(function($keyword) {
return preg_quote($keyword, '/');
}, array_keys($words))) . ')\b/i';
preg_match_all($re, $text, $matches);
foreach ($matches[0] as $keyword) {
echo $keyword, " ", $words_ci[mb_strtolower($keyword)], "\n";
}