2015-05-15 213 views
-3

In $variable I have html code which reads like:`PHP str_replace <tag>東西 - 東西</tag>納入<a href="stuff">Stuff<a href="things">Things?

<tag>Lots of Text Here - More Phrases Here</tag>. 

I'd like to be able to str_replace the string in between the 2 tags

<tag> string </tag> 

I want the new code to read:

<tag><a href="Lots">Lots</a> <a href="of">of</a> 
<a href="text">Text</a> <a href="here">Here</a> - 
<a href="@morephraseshere">@MorePhrasesHere</a></tag> 

I know this might be a lot to str_replace all at once, but if you can at least get either the "Lots of Text Here" to become links, or if you can get the @MorePhrasesHere to become a link it would be amazing.

Or the closest you can get to a full solution would be fantastic as well.

The string of text in $variable changes for each entry. A preg_match or str_explode solution for $variable would be amazing as well if you can't do it in str_replace.

Thank you!

Edit: The objective is to turn every word in the first string into a #hashtag, and every word in the second string into a @username. The server knows how to return valid responses for both types of links.

+0

它是否每次都從開始,最後有? – splash58

+0

是的,這兩個標籤是一致的,裏面的文字會一直改變。在兩個字符串之間總會有一個「 - 」:「 string - string2

+1

你不能使用'str_replace',你不知道里面會有什麼,你可以使用'preg_replace'或'preg_match'。如果你使用'preg_match',你必須在後面建立與找到的值的鏈接。在你的例子中,'text'和'here'是如何鏈接的? – chris85

回答

1

Here's how I'd do this with preg_match, http://php.net/manual/en/function.preg-match.php.表示任何字符,*是一個量詞,意味着0個或更多的前一個字符出現。由於它是.我們允許一切。 ?刪除貪婪所以它正在尋找-的第一次出現,然後我們再次拉動所有其他的東西,直到</tag>

<?php 
preg_match('~<tag>(.*?)-(.*?)</tag>~', '<tag>Lots of Text Here - More Phrases Here</tag>', $found); 
echo '<a href="#' . urlencode(trim($found[1])) . '">' . trim($found[1]) . '</a>' . "\n"; 
echo '<a href="@' . urlencode(trim($found[2])) . '">' . trim($found[2]) . '">' . '</a>' . "\n"; 
?> 

輸出:

<a href="#Lots+of+Text+Here">Lots of Text Here</a> 
<a href="@More+Phrases+Here">More Phrases Here"></a> 

你應該開始學習的元字符和量詞。這將有助於您在將來編寫自己的正則表達式。你應該瀏覽這個網站;它有點長,但也有很多信息,http://www.regular-expressions.info/php.html

+0

是的我會盡力瞭解更多關於正確的正則表達式,特別是考慮到我最近寫了多少,我知道多少。非常感謝您的解決方案和鏈接。我會盡快測試你的代碼,並會閱讀更多內容。再次感謝克里斯! –

0

拿這個代碼。沒有什麼可以解釋的

$title = '<tag>Lots of Text Here - More Phrases Here</tag>'; 

preg_match('/<tag>\s*(.+)\s+-\s+(.+)\s*<\/tag>/', $title, $matches); 
$res = '<tag>'; 
$words = explode(' ', $matches[1]); 
foreach ($words as $word) 
    $res .= '<a href="#'.$word.'">'.$word.'</a> '; 
    $after = str_replace(' ','', $matches[2]); 
$res .= '<a href="@'.$after.'">@'.$after.'</a></tag>'; 
echo $res; 
+0

是的問題是,你正在替換字符串「這裏有很多文字 - 這裏有更多的短語」,但我需要將文字替換爲2個變量。它是「$ title = $ entry-> title;」所以變量將是$ title。克里斯做同樣的事情,他preg_matching字符串,但不是變量。我感謝你嘗試,而代碼實際preg_matched字符串和迴應成功。 –

+0

我特別沒有使用常客,因爲你說不知道他們。使用使代碼變得簡單 – splash58