将字符串转换为数组,然后在每个单词上添加过滤器链接后,将数组打印为原始字符串

时间:2018-09-12 14:55:08

标签: php wordpress

我正在由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

此代码工作正常,但我希望该数组的打印方式应与原始诗歌完全相同。任何帮助或指导将不胜感激。

2 个答案:

答案 0 :(得分:1)

我不知道为什么需要将其拆分为一个数组。您可以使用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);

此时回显将使行之间用换行符(\ n)分隔。要用<br />标签分隔行,您需要对其进行转换

echo nl2br($str);

答案 1 :(得分:0)

这应该能满足您的需求,请尝试一下

<?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);