jobun
jobun

Reputation: 157

How to remove dots from this combination in PHP

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

Answers (6)

gosukiwi
gosukiwi

Reputation: 1575

/\@\w+(\.\w+)?(?<dot>\.)/

That will match all dots and name them in the dot group

Upvotes: 0

neon
neon

Reputation: 421

Try this:

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

Upvotes: 2

stema
stema

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

Toto
Toto

Reputation: 91488

How about:

preg_replace("/(@\S+)\.(?:\s|$)/", "$1", $string);

Upvotes: 0

fab
fab

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

Michael
Michael

Reputation: 12806

preg_replace('/\.( |$)/', '\1', $string);

Upvotes: 0

Related Questions