php
2013-02-26 101 views 0 likes 
0

我有一个关键字“Keyword1”,我有一个文章“keyword1”出现在它的几次。文章中的每个“关键字1”都是通向不同网站的链接。 所以我想每次刷新页面时随机显示一个“keyword1”。如何随机显示文章中的特定关键字

到目前为止,我已经尝试过使用stripos()这样的。

$needle = "keyword1"; 
$haystack = 'this is an article with [keyword1] appearing seral times with different links. [Keyword1] blahblah [keyword1]' ; 

if(stripos($haystack, $needle) !== false){ 


$links = $haystack; 
$links_to_array = explode(" ", $links); 
$randomize = array_rand($links_to_array, 1); 
echo ($links_to_array[$randomize]); 
} 

因此,当我这样做...它不选择关键字1之一,它也随机显示文章中的一个词。您可以复制代码并通过刷新页面来为自己尝试。

我只想要显示一个随机的keyword1。

我该怎么做?

+0

如何'keyword1'如果你想每次都挑它随机的? – 2013-02-26 01:29:04

+0

这是一个通往不同地点的超链接。 – Kibz 2013-02-26 01:30:13

+0

那你为什么不发布相关的'$ haystack',有超链接? – 2013-02-26 01:33:43

回答

1

我不确定你要做什么。但下面的代码可能会有所帮助。我使用的功能preg_match_all找到关键字1的所有出现 - 不区分大小写:/i

<?php 

$needle = "keyword1"; 
$haystack = 'this is an article with [keyword1] appearing seral times with different links. [Keyword1] blahblah [keyword1]' ; 

if(stripos($haystack, $needle) !== false){ 
    preg_match_all('/\[keyword1\]/i', $haystack, $matches); 
    $links_to_array = $matches[0]; 
    $randomize = array_rand($links_to_array, 1); 
    echo ($links_to_array[$randomize]); 
} 
+0

谢谢...正是我在找什么。 :) – Kibz 2013-02-26 01:46:21

+1

hehe :)欢迎您.. – hek2mgl 2013-02-26 01:48:46

相关问题