【问题标题】:How to detect all the text which has an @ sign in a paragraph in php如何在php中检测段落中带有@符号的所有文本
【发布时间】:2016-04-06 08:35:30
【问题描述】:

在我当前的 php 项目中,我正在向后端发送一些带有 @ 符号的特殊文本。我需要检测所有带有@符号的单词并将它们作为一个数组。我正在尝试使用以下正则表达式,但它不起作用,谁能帮我解决这个问题

$text = "my text has some @signs and @names";    
preg_match_all('/(?<!\w)@\w+/', $text, $matches);
print_r($matches);

【问题讨论】:

  • 看来您的代码确实有效:ideone.com/RvFRSA。如果这不是预期的输出,您必须说明缺少的内容。
  • 提供一个可重现的示例以及预期的输出。
  • 请在您提出正则表达式问题时,提供示例输入和输出。没有它,我们就无法测试我们的解决方案。

标签: php arrays regex laravel-5.1


【解决方案1】:

如果您的文本很长,这可能不是最佳解决方案,但这会起作用:

$marked = array();
foreach (explode(' ', $text) as $word) {
    if ($word[0] == '@') {
        $marked[] = $word;
    }   
}

将导致:

Array
(
    [0] => @signs
    [1] => @names
)

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2012-01-29
    相关资源
    最近更新 更多