【问题标题】:preg_replace everything but @ signpreg_replace 除@符号外的所有内容
【发布时间】:2014-02-06 14:13:14
【问题描述】:

我已经搜索过这个例子,但似乎找不到。

我希望用字符串替换所有内容,但 @texthere

$Input = this is @cool isn't it?

$输出 = @cool

我可以使用preg_replace("/@(\w+)/", "", $Input); 删除@cool,但不知道如何做相反的事情

【问题讨论】:

  • preg_match匹配想要的字符串,然后分配$output = $extracted_string

标签: php preg-replace


【解决方案1】:

您可以匹配@\w+,然后替换原始字符串。或者,如果您需要使用preg_replace,您应该可以将所有内容替换为第一个捕获组:

$output = preg_replace('/.*(@\w+).*/', '\1', $input);

使用 preg_match 的解决方案(我认为这会更好):

$matches = array();
preg_match('/@\w+/', $input, $matches);
$output = $matches[0];

以上两种模式都没有解决如何处理多次匹配的输入的问题,例如this is @cool and @awesome, right?

【讨论】:

  • 处理具有多个匹配项的输入的最佳方法是什么?我猜应该是preg_match_all
  • 只需使用preg_match_all 并迭代结果,它将为您提供所有匹配的字符串。
  • 感谢您的帮助,这帮助我找到了可行的解决方案。
  • @helion3:是的,我知道preg_match_all。我只是提到了这两种模式的局限性。使用 preg_match_all 和循环很容易。
猜你喜欢
  • 2013-12-06
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多