我必须处理植物拉丁名称,并且需要对来自数据库的植物名称中的部分单词进行样式设置。名称以原始文本形式存储。
示例字符串:
Androsace angrenica 'Angelica' subsp. Violaceae
想要的结果:
<em>Androsace angrenica</em> 'Angelica' subsp. <em>Violaceae</em>
一些特定的单词将被排除在斜体标签中,如上面的示例和数组中所示
$toFind
。
到目前为止,我得到了每个单词,除了数组中被
<em></em>
包裹的单词,如下所示:
<em>Androsace</em> <em>angrenica</em> 'Angelica' subsp. <em>Violaceae</em>
我希望能够防止像名称的第一部分一样跟随
</em> <em>
并将它们加入到第一个示例中所示的单个标签包装中。
# Array of words not be wraped in italic
$toFind = ["subsp.", "var.", "f.", "(voir)", "hybride"];
# Plant name
$name = "Androsace angrenica 'Angelica' subsp. Violaceae";
# Make an array of words from the name
$words = explode( " ", $name );
$newWords = [];
foreach( $words as $key => $word ) {
if( in_array( $word, $toFind )) {
$newWords[] = $word;
}else{
# Catch the word or words surrounded by single quotes like 'Angelica'
$isHybrid = preg_match_all( "/'([^.]*?)'/", $word, $matches, PREG_PATTERN_ORDER );
if( $isHybrid ){
# No tags required
$newWords[] = $word ;
}else{
# Tags required for these words
$newWords[] = "<em> ". $word . "</em>";
}
}
}
echo implode(" ", $newWords);
请注意,此示例名称是多种可能性之一,如下所示:
Allium obliquum
Allium ostrowkianum (voir) A. oreophilum
Allium senescens subsp. glaucum
Allium sikkimense
Androsace × pedemontana
您可以考虑处理
implode()
结果:
echo str_replace("</em> <em>", " ", implode(" ", $newWords));
在
</em> <em>
内爆后,这会将
的所有实例替换为 $newWords
。