Reputation: 157
I have this combination in a string:
"I am tagging @username1.blah. and @username2.test. and @username3."
I tried this:
preg_replace('/\@^|(\.+)/', '', 'I am tagging @username1.blah. and @username2.test. and @username3. in my status.');
But the result is:
"I am tagging @username1blah and @username2test and @username3 in my status"
The above result is not what I wanted.
This is what I want to achieve:
"I am tagging @username.blah and @username2.test and @username3 in my status."
Could someone help me what I have done wrong in the pattern?
Many thanks, Jon
Upvotes: 2
Views: 1576
Reputation: 1575
/\@\w+(\.\w+)?(?<dot>\.)/
That will match all dots and name them in the dot group
Upvotes: 0
Reputation: 93026
This will replace dots at the end of "words" that are starting with @
$input = "I am tagging @username1.blah. and @username2.test. and @username3. in my status.";
echo preg_replace('/(@\S+)\.(?=\s|$)/', '$1', $input);
(@\S+)\.(?=\s|$)
will match a dot at the end of a non whitespace (\S
) series when the dot is followed by whitespace or the end of the string ((?=\s|$)
)
Upvotes: 1
Reputation: 1859
I don't like regex very much, but when you are sure that the dots you want to remove are always followed by a space, you could do something like this:
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
Upvotes: 3