2015-04-23 68 views
0

我想删除以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,直到不再是这种情况。 如何将其转换为正则表达式?

回答

0

您可以使用类似如此的东西:(#[^# ]+?)+$并将其替换为空字符串。

举例here。由于您有非ASCII字符,因此.运算符(匹配任何字符)应该可以帮助您处理任何字符。

0

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

/(#\S+)*$/g 

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

+0

我尝试过了,得到这个错误:'警告:preg_match_all() function.preg-match-all]:未知修饰符'g'' PHP:'$ tweet =“hello world #dontremove我foobar http://example.com/#dontremoveme #remove #removeme#removeüäüö“; preg_match_all(“/(#\ S +)* $/g”,$ tweet,$ matches); var_dump($ matches);'我需要改变什么? – Tom

+0

请尝试以下操作: '$ re =“/(#\\ S +)* $ /”; $ str =“hello world #dontremoveme foobar http://example.com/#dontremoveme #remove #removeme#removeüäüö”; preg_match_all($ re,$ str,$ matches);' 这是生成的代码,你可以在这里找到:https://regex101.com/r/eH4bJ2/1#code_0 – jonas

+0

这可以工作,但'print_r $匹配)'输出2个数组 - 如何获得一个数组中的所有标签? – Tom

0

这将做的工作:

$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 
+0

我刚刚试过你的例子,“$ res”回显为空。有最小值吗? PHP版本需要或我错过了什么?谢谢 – Tom

+0

@Tom:我的php版本很老:'PHP 5.4.4-9(cli)(built:Oct 26 2012 13:00:59)'。你做了代码的复制/粘贴吗?我已经得到了我所写的。 – Toto

+0

是的,我用复制和粘贴,并没有什么别的PHP文件。我的PHP版本是:'PHP Version 5.3.28-nmm2'任何想法? – Tom