user3741635
user3741635

Reputation: 862

How to replace string begining with @@ only and not @ or @@@?

Consider the string

$str="hello @jack, tell @sam,@@jake and @@sam and @@@jake and @tom/@jim and @@jake hello"

Is it possible to replace a specific username (for example jack) that begins with @@ only and not @ or @@@?

What I mean is that, is it possible to only effect a string beginning with a specific number of @?

This is what I tried

$user = "jack";
$str = preg_replace('~@@'.$user.'~', '[['.$user.']]', $str);

the problem is that this replaces both @@jack and @@@jack with jack and @jack.

Upvotes: 1

Views: 66

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You need to specify the necessary number of @ and use a negative look-behind:

(?<!@)@@jake\b

See demo. This will match jake as a whole word (due to word boundary \b) preceded with only 2 @s (as the (?<!@) negative look-behind checks if there is a @ before the first @, and if yes, does not match the first @).

To match a word preceded with only 4 @ symbols, use (?<!@)@{4}word\b. For only one @, use (?<!@)@word\b.

Sample code demo:

$str="hello @jack, tell @sam,@@jake and @@sam and @@@jake and @tom/@jim and @@jake hello";
$user = "jake";
$number_of_prefixes = 2;
$str = preg_replace('~(?<!@)@{' . $number_of_prefixes . '}'.$user.'\b~', '[['.$user.']]', $str);
echo $str;

Output: hello @jack, tell @sam,[[jake]] and @@sam and @@@jake and @tom/@jim and [[jake]] hello

Upvotes: 2

Related Questions