2012-03-30 50 views
2

删除点我有一个字符串,这个组合:如何从这种组合在PHP

"I am tagging @username1.blah. and @username2.test. and @username3." 

我尝试这样做:

preg_replace('/\@^|(\.+)/', '', 'I am tagging @username1.blah. and @username2.test. and @username3. in my status.'); 

但结果是:

"I am tagging @username1blah and @username2test and @username3 in my status" 

以上结果不是我想要的。

这是我想达到的目标:

"I am tagging @username.blah and @username2.test and @username3 in my status." 

有人能帮助我什么,我做错了的格局?

非常感谢, 乔恩

回答

1

这将替换的“字”结束点被开始@

$input = "I am tagging @username1.blah. and @username2.test. and @username3. in my status."; 
echo preg_replace('/(@\S+)\.(?=\s|$)/', '$1', $input); 

(@\S+)\.(?=\s|$)将在非空白的端部相匹配的点(\S)系列当点是其次是空白或字符串((?=\s|$)

2

试试这个:

preg_replace('/\.(\s+|$)/', '\1', $r); 
+0

感谢您的回答,这是非常有用的 - 但我编辑的问题,因为我想这些更改只适用于以'@'符号开头的单词。非常感谢。 – jobun 2012-03-30 07:35:34

3

我不喜欢正则表达式非常多,但是当您确定要删除的总是后面加一个空格点,你可以做这样的事情:

php > $a = "I am tagging @username1.blah. and @username2.test. and @username3."; 
php > echo str_replace(". ", " ", $a." "); 
I am tagging @username1.blah and @username2.test and @username3 
+1

即使该单词不以“@”开头,也会删除点。 – Toto 2012-03-31 08:44:41

0

如何:

preg_replace("/(@\S+)\.(?:\s|$)/", "$1", $string); 
0
/\@\w+(\.\w+)?(?<dot>\.)/ 

,将符合所有点和点组中为它们命名结束