2013-04-13 114 views
-2

我想用PHP来替换文本字符串中带有加标签的单词。替换字符串中的文本

我的字符串:

"Working on some cool things for shareit.me #ui #webdesign #ux" 

我想封装用span标签每个哈希标签的关键字给他们一个不同的颜色。我怎样才能做到这一点?

谢谢!

+0

有时候搜索可以很有帮助的:http://stackoverflow.com/questions/3426265/php-string-replace-match-whole-word(通过搜索Google找到'PHP替换t中的单词ext') –

+0

请参阅http://stackoverflow.com/a/4277114/1493698 – Antony

回答

0

与 '了preg_replace' 尝试像

preg_replace('/(^|\s)#(\w+)/','<span style="color:green;">\2</span>',$my_string); 
+0

它对你有用吗? – Gautam3164

0

,如果你希望每个标签不同的颜色

str_replace(array('#ui', '#webdesign', '#ux'), array('<span style="color:red">#ui</span>', '<span style="color:green">#webdesign</span>', '<span style="color:blue">#ux</span>'), "Working on some cool things for shareit.me #ui #webdesign #ux"); 

,如果你想更换所有#tag

preg_replace('/#(\w\d+?)/', '<span style="color: red">#$1</span>', "Working on some cool things for shareit.me #ui #webdesign #ux");