【问题标题】:Remove hashtags from the end of a sentence从句子末尾删除主题标签
【发布时间】:2015-04-23 19:53:36
【问题描述】:

我想删除以space# 符号开头的文本末尾的所有单词。 不应删除句子中的 URL 或主题标签。

示例文本:

hello world #dontremoveme foobar http://example.com/#dontremoveme #remove #removeme #removeüäüö

我试过了,但它删除了所有标签:

$tweet = "hello world #dontremoveme foobar http://example.com/#dontremoveme #remove #removeme #removeüäüö";
preg_match_all("/(#\w+)/", $tweet, $matches);
var_dump( $matches );

我的想法是检查从文本末尾开始的每个单词是否有前导 # 和前面的 space,直到不再是这种情况。 如何将其翻译成正则表达式?

【问题讨论】:

    标签: php regex hashtag


    【解决方案1】:

    您可以使用类似这样的内容:( #[^# ]+?)+$ 并将其替换为空字符串。

    here 提供了一个示例。由于您有非 ASCII 字符,. 运算符(匹配任何字符)应该可以帮助您处理任何字符。

    【讨论】:

      【解决方案2】:

      以下正则表达式匹配行尾以[Space]# 开头的所有单词。

      /( #\S+)*$/g
      

      https://regex101.com/r/eH4bJ2/1

      【讨论】:

      • 我试了一下,得到了这个错误:Warning: preg_match_all() [function.preg-match-all]: Unknown modifier 'g' PHP:$tweet = "hello world #dontremoveme foobar http://example.com/#dontremoveme #remove #removeme #removeüäüö"; preg_match_all("/( #\S+)*$/g", $tweet, $matches); var_dump( $matches );我需要改变什么?
      • 尝试以下操作:$re = "/( #\\S+)*$/"; $str = "hello world #dontremoveme foobar http://example.com/#dontremoveme #remove #removeme #removeüäüö"; preg_match_all($re, $str, $matches); 这是生成的代码,您可以在此处找到:regex101.com/r/eH4bJ2/1#code_0
      • 可行,但print_r($matches) 输出 2 个数组 - 如何在一个数组中获取所有标签?
      • 如果您在正则表达式周围添加一组括号,则第一个匹配项应该是所有主题标签:$re = "/(( #\\S+)*)$/",尝试一下...否则,它是 PHP 问题,而不是正则表达式问题,你可以用标准的 PHP 来解决它。
      【解决方案3】:

      这样就可以了:

      $tweet = "hello world #dontremoveme foobar http://example.com/#dontremoveme #remove #removeme #removeüäüö";
      $res = preg_replace("/ #\p{L}+\b(?!\s+\p{L})/u", '', $tweet);
      echo $res,"\n";
      

      输出:

      hello world #dontremoveme foobar http://example.com/#dontremoveme
      

      【讨论】:

      • 我刚试过你的例子,“$res”回显是空的。有分钟吗?需要 PHP 版本或我想念什么?谢谢
      • @Tom:我的 php 版本很旧:PHP 5.4.4-9 (cli) (built: Oct 26 2012 13:00:59)。您是否复制/粘贴了代码?我已经完全掌握了我所写的内容。
      • 是的,我使用了复制和粘贴,PHP 文件中没有其他内容。我的 PHP 版本是:PHP Version 5.3.28-nmm2 有什么想法吗?
      • @Tom:可能是5.3 不处理 unicode 属性 (\p{L}),请尝试使用 [a-züäö]
      • 如何检查问题是否是我的 PHP 版本5.3.28-nmm2
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      相关资源
      最近更新 更多