2015-11-04 126 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