【问题标题】:Regex is not including spaces正则表达式不包括空格
【发布时间】:2021-03-14 00:48:10
【问题描述】:

我正在使用一些 atwho.js 来允许使用 @ 链接到用户个人资料。

例如@User1 @User2 @User3,所有这些都会链接到他们的个人资料。

我从 regexr.com 获得了正确的反馈,但它没有翻译,

不包括空格

这是我的记录在数据库中显示的内容:

<p><a href=/profiles/Richard Skiles>@Richard Skiles</a></p>

输出如下:

<p><a href=/profiles/Richard>@Richard Skiles</a></p>

这里有一些代码:

public function setBodyAttribute($body)
{
    $find = ['/@([\w\- ]+)/'];
    $replace = ['<a href=/profiles/$1>$0</a>'];
    $this->attributes['body'] = preg_replace($find, $replace, $body);
}

希望有人可以在这里帮助我。不胜感激,谢谢!!

【问题讨论】:

  • 您是否尝试将空格替换为“%20”或将 URL 部分放在引号中? (

    @Richard Skiles

标签: php regex laravel preg-replace preg-match


【解决方案1】:

我看到您在字符集中添加了一个空格,但 preg_replace 与这样的空格不匹配。他们使用\s

public function setBodyAttribute($body)
{
    $find = ['/@([\w\-\s]+)/']; // I added the \s to match the spaces
    $replace = ['<a href=/profiles/$1>$0</a>'];
    $this->attributes['body'] = preg_replace($find, $replace, $body);
}

【讨论】:

  • 你好。我确实试过这个。然而它没有用。谢谢。
  • 你能用$body更新你的问题吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 2013-01-12
  • 1970-01-01
相关资源
最近更新 更多