我有一個這樣的字串
$content="#Love #Lovestories #Lovewalapyar";想讓這些標簽可以點擊。
我有一個陣列。
我有一個陣列。
$tags=
(
[0] => stdClass Object
(
[TOPIC_ID] => 132[/span
[TOPIC_NAME] => Love
[TOPIC_URL] => http:/local/topic/132/love .
)
[1] => stdClass Object >。
(
[TOPIC_ID] => 3347[/span
[TOPIC_NAME] => LoveStories
[TOPIC_URL] => http:/local/topic/3347/lovestories .
)
[2] => stdClass Object >。
(
[TOPIC_ID] => 43447[/span
[TOPIC_NAME] => lovewalapyar
[TOPIC_URL] => http:/local/topic/43447/lovewalapyar .
)
);
用這個來使標簽可以點擊。
foreach($tags as $tag){
$content=str_ireplace('#'.$tag->TOPIC_NAME, '<a href="'/span>。 $tag->TOPIC_URL.'" title="'/span>. htmlentities($tag->TOPIC_NAME).'" >#'. $tag->TOPIC_NAME.'</a>', $content)。)
}
得到這個。 它只替換了愛而不是其他的字串。
試圖替換/使這些標簽可點擊。
如果有任何幫助,我們將非常感激。
uj5u.com熱心網友回復:
原因很簡單。你有一些標簽是其他標簽的子串。 為了避免這種重疊問題,你可以以非遞增的方式對你的陣列進行排序,先替換較長的字串,后替換較短的字串,這樣就完全避免了重疊問題,如下:
<?php
usort($tags,function($a, $b){
return strlen($b->TOPIC_NAME) <=> strlen($a-> TOPIC_NAME) 。
});
更新:
你在<a></a>內的hashtag文本導致str_ireplace重新考慮它。為此,你需要在一個陣列中傳遞陣列值和它們各自的替換,或者,你可以使用一個HTML字符物體#來代替添加#,它將被str_ireplace()忽略,并將正常作業,如下所示:
'<a ...>#'.$tag->TOPIC_NAME.'</a> ' /span>。
更新的片段:
<?php
usort($tags,function($a, $b){
return strlen($b->TOPIC_NAME) <=> strlen($a-> TOPIC_NAME) 。
});
foreach($tags as $tag){
$content = str_ireplace('#'.$tag->TOPIC_NAME, '<a href="'/span>。 $tag->TOPIC_URL.'" title="'/span>.htmlentities($tag->TOPIC_NAME).'">& #35; '. $tag->TOPIC_NAME.'</a>', $content)。)
}
uj5u.com熱心網友回復:
我將使用正則運算式/#(w*)/(標簽和空白)和preg_replace()來替換所有出現的內容。
像這樣:
$content = "#Love #Lovestories #Lovewalapyar"/span>。
$pattern = '/#(w*)/';
$replacement = '<a href="#$1">$1</a> ';
preg_replace($pattern, $replacement, $content) 。
這將使你:
< a href="#Love">Love</a>/span>
<a href="#Lovestories"/span>> Lovestories</a>。
<a href="#Lovewalapyar"/span>> Lovewalapyar</a>。
你可以在這里在線測驗那個regex.
。如果你需要一些高級邏輯,就像Magnus Eriksson在評論中提到的那樣,你可以使用preg_match_all并在找到的匹配中進行迭代。
像這樣:
$content = "#Love #Lovestories #Lovewalapyar"/span>。
$pattern = '/#(w*)/'。
preg_match_all($pattern, $content, $matches) 。
foreach ($matches[1] as $key => $match) {
// do whatever you need here, you might want to use $tag = $tags[$key];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/307856.html
標籤:
上一篇:如何在php中增加完整的字串?

