我正在开发一个由WordPress提供支持的诗歌网站。我想将字符串(实际上是帖子内容(转换为数组,以添加指向每个单词的链接,以将具有相同单词的其他诗歌搜索到我的网站数据库中。 到目前为止,我的工作是:
<?php
//sample poem
$str = 'We two, how long we were fool’d,
Now transmuted, we swiftly escape as Nature escapes,
We are Nature, long have we been absent, but now we return,
We become plants, trunks, foliage, roots, bark,
We are bedded in the ground, we are rocks,
We are oaks, we grow in the openings side by side,
We browse, we are two among the wild herds spontaneous as any,';
$arr = preg_split("/[s,]+/", $str);
foreach ($arr as $poemarr) {
$poem = "<a href = https://www.google.com>" . $poemarr . "</a>"; //sample google link but actually want to add WordPress filter to search other poems having same word.
echo $poem . " "; //here what should I do to print the string to look like exactly the same as $str???
}
?>
代码的输出为:
We two how long we were fool’d Now transmuted we swiftly escape as Nature escapes We are Nature long have we been absent but now we return We become plants trunks foliage roots bark We are bedded in the ground we are rocks We are oaks we grow in the openings side by side We browse we are two among the wild herds spontaneous as any
这段代码工作正常,但我希望该数组应该像原始诗歌一样打印。任何帮助或指导将不胜感激。
我不知道为什么需要将其拆分为数组。您只需使用 preg_replace 将所有实例包装在一个链接中。
这将搜索任何字符串,直到,但不包括空格逗号或句点。然后在链接中包装相同的单词。
<?php
$str = <<<EOD
We two, how long we were fool’d,
Now transmuted, we swiftly escape as Nature escapes,
We are Nature, long have we been absent, but now we return,
We become plants, trunks, foliage, roots, bark,
We are bedded in the ground, we are rocks,
We are oaks, we grow in the openings side by side,
We browse, we are two among the wild herds spontaneous as any
EOD;
$str = preg_replace("/([^ ,.n]+)/", '<a href="https://www.google.com/search?q=$1">$1</a>', $str);
此时回显时,行之间将用换行符 (( 分隔。要用<br />
标签分隔行,您需要转换它们
echo nl2br($str);
这应该可以感受到您的需求,请尝试一下
<?php
//sample poem
$str = 'We two, how long we were fool’d,
Now transmuted, we swiftly escape as Nature escapes,
We are Nature, long have we been absent, but now we return,
We become plants, trunks, foliage, roots, bark,
We are bedded in the ground, we are rocks,
We are oaks, we grow in the openings side by side,
We browse, we are two among the wild herds spontaneous as any,';
$words = preg_split("/[s,]+/", $str);
$wordToLinks = [];
foreach ($words as $word) {
$wordUsages = ''; // Here do your wp queries to get usage of the word
$wordLink = 'sprintf('<a href=%s>%s</a>', $wordUsages, $word); //sample google link
$wordToLinks[$word] = $wordLink;
}
// Replace the word in the text (no ',' or 't' ..)
// By the link to the word (please replace by your research link)
echo str_replace(array_keys($wordToLinks), array_values($wordToLinks), $str);