Consider I have a text of 开发者_StackOverflow社区300-400 words with some basic html. Example:
<p>text text word1 text text text filament text text text text text text text text</p>
<p>text text text text text text text text text text text text text text text</p>
And I have a list of keyphrase with their urls associated (about 1000 records)
word1 word2 => 'url'
house home => 'url1'
flower filament => 'url2'
I need to place the url for the corrispondent word found in text. Example:
<p>text text <a href="url">word1</a> text [etc..]
I Know I can use a simple str_replace or preg_replace. But i dont' want to add to many links. Out of 300-400 words i don't want to put more than 5-6 links.
What can I Do?
use preg_replace() with the limit parameter, of course it will be the first X replacements, which may or may not be what you want
A small example that justs makes the first instance of each desired word bold. Should be easy to do other stuff with it as well. :)
<?
// Your text
$s = <<<YourText
<p>text text word1 text text text filament text text text text text text text text</p>
<p>text text text text text text text text text text text text text text text</p>
YourText;
// The words you want to highlight
$linkwords = array('text', 'word1', 'filament');
// Split the string by using spaces
$words = explode(' ', $s);
print_r($words);
// Words you have highlighted already.
$done = array();
// Loop through all words by reference
foreach ($words as &$word)
{
// Highlight this word?
if (array_search($word, $linkwords) !== false)
{
// Highlighted before?
if (array_search($word, $done) === false)
{
// Remember it..
$done[] = substr($word,0);
// And highlight it.
$word = '<b>'.$word.'</b>';
}
}
}
echo implode(' ', $words);
First, from your question I figured that words/links ratio would be around 60
. So, to give you an example, do the following:
define('WLRATIO', 60);
$mytext = "text text ..... ";
// Rough estimation of word count
$links = count(explode(' ', $mytext)) / WLRATIO;
$keywords = array(
'foo' => 'url1',
'bar' => 'url2'
...
);
$keys = array_keys($keys);
while ( $links-- ) {
$n = rand(0, count($keys)-1);
$mytext = preg_replace('/'+$keys[$n]+'/', '<a href="'+$keywords[$keys[$n]]+'">'+$keys[$n]+'</a>', $mytext, 1);
}
echo $mytext;
精彩评论