2014-06-20 17 views
0

我有以下字符串:PHP - 在字符串的超鏈接替換各種案例類型,並保留原有的情況下

「這是我的字符串MYTEXT的三個實例,這是第一個實例這是第二個實例。 Mytext,這是mytext的第三例。「

我需要用包裝在標籤中的版本來替換Mytext(所有三個實例)的每個實例,所以我想在每個實例周圍包裝HTML標籤。這很容易,我沒有這個問題。我的問題是 - 我怎麼做,同時保留每個實例的原始情況。我需要的輸出是:

「這是我的三個MYTEXT實例的字符串,這是第一個實例,這是Mytext的第二個實例,這是mytext的第三個實例。

我一直在尋找str_ireplace和preg_teplace,但他們似乎都沒有做這項工作。

任何想法?

在此先感謝。

回答

0

您可以使用反向引用來實現:

preg_replace('/mytext/i', '<a href="foo.html">\\0</a>', $str); 

\\0反向引用在替換字符串將整場比賽被替換,有效地保持了原有的情況。

0

另一種方法是使用基礎知識的低效率解決方案。

<?php 

    $string = "This is my string with three instances of MYTEXT. That was the first instance. This is the second instance of Mytext. And this is the third instance of mytext."; 
    $copyOfString = $string; // A copy of the original string, so that you can use the original string later. 

    $matches = array(); // An array to fill with the matches returned by the PHP function using Regular Expressions. 
    preg_match_all("/mytext/i", $string, $matches); // The above-mentioned function. Note that the 'i' makes the search case-insensitive. 

    foreach($matches as $matchSubArray){ 
     foreach($matchSubArray as $match){ // This is only one way to do this. 
      $replacingString = "<b>".$match."</b>"; // Edit to use the tags you want to use. 
      $copyOfString = str_replace($match, $replacingString, $copyOfString); // str_replace is case-sensitive. 
     } 
    } 

    echo $copyOfString; // Output the final, and modified string. 

?> 

注意:正如我在開始時暗示的那樣,這種方法使用不好的編程習慣。

相關問題