2015-11-04 177 views
0

我試圖將^更換爲<span>。但是,我失敗了。我嘗試了str_replace,但無法正常工作。更改字符串值

所以,我原來的值是:

^ffcb4a Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon&#039;t lose this. 

你可以看到,有一個顏色值,開始與^,我想替換爲:'<span style=color"#ffcb4a">

但我str_replace,我得到這個:

<span style='color:#'ffcb4a Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon&#039;t lose this. 

就像你看到的,這是行不通的。

$item_description = str_replace('^', "<span style='color:#'" . '', $item_description); 

回答

0

你需要爲此使用正則表達式。

$item_description = '^ffcb4a Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon\'t lose this.'; 
echo preg_replace('/\^(.*?)\h/', 
'<span style="color:#$1">', 
$item_description); 

輸出:

<span style="color:#ffcb4a">Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon't lose this. 

也不清楚你想要的span結束..

此正則表達式捕獲^和第一水平的白色空間之間的一切。

Regex101演示:https://regex101.com/r/bA4dC8/1

您不能使用str_replace,因爲你不知道在哪裏關閉span

如果你想^後的前6個字符拉你可以改變

(.*?)\h 

(.{6}) 

它說任何6個字符。

例子:

$item_description = '^ffcb4a Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon\'t lose this.'; 
    echo preg_replace('/\^(.{6})/', 
    '<span style="color:#$1">', 
    $item_description); 
+0

謝謝!我非常感激。而且,如果我的文本與顏色「合併」?例如:^ ffcb4aSpecial – Peter

+0

您可以在'^'後拉前6個字符。它會始終是6個字符.. – chris85

+0

更新爲這種情況。 – chris85