2013-04-18 19 views
1

我想根據簡單標記更改部分字符串的方法。例如:PHP:選擇字符串的一部分(從)並對其應用更改

$string = "I'm student (at JIC college), and I'm GENIUS."; 

我想括號之間進行選擇at JIC college或任何文字和改變它們的顏色。 (我知道如何改變他們的顏色)。但如何選擇它改變它然後把它放回去。以及如何做到這一點,即使我有一個以上的括號。

$string = "I'm student (at JIC college), and I'm GENIUS (not really)."; 
+0

如果你有嵌套括號,該怎麼辦?像對方括號一樣? – 1337holiday 2013-04-18 06:20:51

+0

'preg_replace()'做你想要的嗎? – Barmar 2013-04-18 06:23:51

+0

@ 1337holiday儘管我想改變裏面的東西像'(aaa(asddsd)asasd)'我想改變這個'aaa(asddsd)asasd' ...這將會很難嗎? – 2013-04-18 06:25:07

回答

2

你可以使用一個preg_replace實現這一目標。

$string = "I'm student (at JIC college), and I'm GENIUS (not really)."; 

$string = preg_replace('/\(([^\)]+)\)/', '<span style="color:#f00;">$1</span>', $string); 

不幸的是,這個例子有點不清楚,因爲你選擇的封裝在正則表達式中丟失並且需要轉義。如果你想讓代碼變得清晰,我會使用括號以外的東西!之間

0

您可以使用explode()

$string = "I'm student (at JIC college), and I'm GENIUS (not really)."; 

$pieces = explode("(", $string); 

$result = explode(")", $pieces[1]); 

echo $result[0]; // at JIC college 
-1

可以實現這一目標使用正則表達式:

$colorized = preg_replace('/(\(.*?\))/m', '<span style="color:#f90;">($1)</span>', $string); 
+0

添加另一個大括號? – BlitZ 2013-04-18 06:45:37

+0

@CORRUPT如果你仔細觀察,你會注意到在我寫答案的時候沒有要求。無論如何,我正在研究解決方案,因此一旦準備就緒,我會更新這篇文章 – 2013-04-18 06:53:40

0

獲取字符串()這個函數

function get_string_between($string, $start, $end){ 
    $string = " ".$string; 
    $ini = strpos($string,$start); 
    if ($ini == 0) return ""; 
    $ini += strlen($start); 
    $len = strpos($string,$end,$ini) - $ini; 
    return substr($string,$ini,$len); 
} 

$fullstring = "this is my [tag]dog[/tag]"; 
$parsed = get_string_between($fullstring, "[tag]", "[/tag]"); 

echo $parsed; // (result = dog) 

,並改變顏色。

相關問題