【问题标题】:change string where find @username in php [closed]更改在php中找到@username的字符串[关闭]
【发布时间】:2016-11-18 07:17:37
【问题描述】:

如何在 find 的完整字符串中替换 @username。

示例: 原始字符串:"Hello @mike and @max how are you";

预期结果字符串:"Hello <a href="#">@mike</a> and <a href="#">@max</a> how are you'

我尝试使用 strpos 并爆炸,但没有得到解决方案。

请帮助任何人!谢谢。

【问题讨论】:

  • 显示你的代码,到目前为止你已经尝试过什么
  • 为什么需要正则表达式?看看str_replace
  • 好吧,除了str_replace explode/implode 的基本解决方案非常简单之外,应该注意的是,正则表达式也是一个不错的解决方案, 因为否则@max 的值也可能插入到@maximilian

标签: php html regex


【解决方案1】:

试试这个正则表达式:

$Output = preg_replace("/(\@\w+)/", "<a href='#'>$1</a>", $Original_String);

http://www.phpliveregex.com/p/hVf

【讨论】:

  • 这很棒。也感谢您的网站参考
  • 非常感谢@Andreas
  • 没问题,你也应该感谢@jitendrapurohit。他纠正了我的错误。
  • @flex 如果您发现答案正确,您应该接受答案。
【解决方案2】:

可能是这样的:

$orig = "Hello @mike and @max how are you";
$arr = explode(" ", $orig);
$newArr = array();

foreach ($arr as $word) {
    $tmp = $word;
    if ($word[0] == '@') {
        $tmp = '<a href="#">'.$word.'</a>';
    }
    $newArr[] = $tmp;
}

$newStr = implode(" ", $newArr);

【讨论】:

  • &lt;sometag&gt;@max&lt;/sometag&gt; 失败,因为没有空格 - 或者名称后面可能是逗号或点之类的东西。
【解决方案3】:

你也可以使用函数str_replace

您可以在此处阅读更多信息http://php.net/manual/en/function.str-replace.php

$intro   = 'Hello';
$user    = 'Person';
$message = 'Hope your day is going well.';

$source = '@intro, @user!  @message';
$search = ['@intro','@user', '@message'];
$replace = [$intro, $user, $message];

$message = str_replace($search, $replace, $source);
var_dump($message);

【讨论】:

  • 这与问题有什么关系?这不是 OP 要求的,还是我遗漏了什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-27
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多