php只从数组中获取第一个出现的单词
我有一个从数据库中提取的标签数组,我将标签导出到标签云中。我只想得到这个词的第一个实例。例如:php只从数组中获取第一个出现的单词,php,regex,dynamic-data,strstr,Php,Regex,Dynamic Data,Strstr,我有一个从数据库中提取的标签数组,我将标签导出到标签云中。我只想得到这个词的第一个实例。例如: $string = "test,test,tag,tag2,tag3"; $getTags = explode("," , $string); foreach ($getTags as $tag ){ echo($tag); } 这将输出测试标签两次。起初,我认为我可以使用stristr来执行以下操作: foreach ($getTags as $tag ){
$string = "test,test,tag,tag2,tag3";
$getTags = explode("," , $string);
foreach ($getTags as $tag ){
echo($tag);
}
这将输出测试标签两次。起初,我认为我可以使用stristr
来执行以下操作:
foreach ($getTags as $tag ){
$tag= stristr($tag , $tag);
echo($tag);
}
这显然是愚蠢的逻辑,不起作用,stristr
似乎只会替换第一次出现的内容,因此类似“test 123”的内容只会删除“test”并返回“123”。我已经看到,这也可以用regex完成,但我还没有找到一个动态的exmaple
谢谢,布鲁克 编辑:
unique\u array()
在使用静态字符串时有效,但不会处理数据库中的数据,因为我使用while循环获取每行数据
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
if ($getTag_data)
{
while ($rowTags = mysql_fetch_assoc($getTag_data))
{
$getTags = array_unique(explode("," , $rowTags['tags']));
foreach ($getTags as $tag ){
echo ($tag);
}
}
}
使用array\u unique()
我相信php的array_unique正是您所需要的:
将您的单词用作字典的键,而不是值
$allWords=array()
foreach(explode("," , $string) as $word)
$allWords[$word]=true;
//now you can extract these keys to a regular array if you want to
$allWords=array_keys($allWords);
当你这么做的时候,你也可以数一数
$wordCounters=array()
foreach(explode("," , $string) as $word)
{
if (array_key_exists($word,$wordCounters))
$wordCounters[$word]++;
else
$wordCounters=1;
}
//word list:
$wordList=array_keys($wordCounters);
//counter for some word:
echo $wordCounters['test'];
是否在迭代数组之前使用该函数?它删除每个重复的字符串并返回唯一的函数 我假设表中的每一行都包含多个标记,标记之间用coma分隔,如下所示:
Row0: php, regex, stackoverflow
Row1: php, variables, scope
Row2: c#, regex
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
$tags = explode("," , $row['tags']);
foreach($tags as $t) {
$getTags[$t] = isset($getTags[$t]) ? $getTags[$t]+1 : 1;
}
}
}
//display
foreach ($getTags as $tag => $count) {
echo "$tag ($count times)";
}
如果是这种情况,请尝试以下方法:
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
//fetch all the tags you found and place it into an array (with duplicated entries)
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
array_merge($getTags, explode("," , $row['tags']);
}
}
//clean up duplicity
$getTags = array_unique($getTags);
//display
foreach ($getTags as $tag ) {
echo ($tag);
}
我要指出,这是没有效率的
另一种选择(这里已经提到)是将标记用作数组键,其优点是能够轻松地对它们进行计数。你可以这样做:
Row0: php, regex, stackoverflow
Row1: php, variables, scope
Row2: c#, regex
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
$tags = explode("," , $row['tags']);
foreach($tags as $t) {
$getTags[$t] = isset($getTags[$t]) ? $getTags[$t]+1 : 1;
}
}
}
//display
foreach ($getTags as $tag => $count) {
echo "$tag ($count times)";
}
- 请记住,这些代码都没有经过测试,这只是为了让您了解其中的含义