ilpaijin
ilpaijin

Reputation: 3695

preg_replace only substring before defined char

I'm trying to replace chars not [A-Z] and before the @ inside a string. So this

[email protected]

needs to become:

A***********[email protected]

I tried with:

$string = '[email protected]';
$pattern = '/(?<!@)[^A-Z@\.]/';
$replacement = '*';

$replace = preg_replace($pattern, $replacement, $tring);

but the result is

'A***********Z@d*****.***'

So I can't find the way how to avoid the replacement of @domain.tld by only using preg_replace().

domain.tld can be anything so I can't use (?<[email protected]) in the $pattern var.

Upvotes: 0

Views: 171

Answers (1)

nickb
nickb

Reputation: 59699

You can just assert that from the current position, match [^A-Z], then make sure you can consume any number of characters but still hit the @:

$pattern = '/[^A-Z](?=[^@]*@)/';

Produces:

A***********[email protected]

Upvotes: 2

Related Questions