2012-03-30 23 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>\.)/ 

,將符合所有點和點組中爲它們命名結束