-2

I would like to use PHP to replace hash-tagged words in strings of text.

My String:

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

I would like to encapsulate each hash-tagged keyword with span tags to give them a different color. How can I do this?

Thanks!

  • Sometimes a search can be very helpful: http://stackoverflow.com/questions/3426265/php-string-replace-match-whole-word (found by searching Google for 'PHP replace words in text') – Jared Ng Apr 13 '13 at 05:32
  • See http://stackoverflow.com/a/4277114/1493698 – Antony Apr 13 '13 at 05:32

2 Answers2

0

Try with 'preg_replace' like

preg_replace('/(^|\s)#(\w+)/','<span style="color:green;">\2</span>',$my_string);
GautamD31
  • 28,552
  • 10
  • 64
  • 85
0

if you want each tag different color

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");

if you want replace all #tag

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