【问题标题】:Replacing text within a string [duplicate]替换字符串中的文本[重复]
【发布时间】:2013-04-05 18:18:08
【问题描述】:

我想使用 PHP 来替换文本字符串中带有哈希标记的单词。

我的字符串:

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

我想用 span 标签封装每个带有哈希标签的关键字,以赋予它们不同的颜色。我该怎么做?

谢谢!

【问题讨论】:

标签: php


【解决方案1】:

尝试使用 'preg_replace' 之类的

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

【讨论】:

  • 它对你有用吗??
【解决方案2】:

如果你想要每个标签不同的颜色

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2020-10-21
    • 2016-09-22
    • 2016-01-08
    • 2011-10-10
    • 2019-04-03
    • 2021-06-17
    相关资源
    最近更新 更多