Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ninj4df's avatar

PHP regex help - hide numbers but not when they are on a specific url

Hello there.

I have a regex to hide all phone numbers, but it also hides them when someone sends a url of my website.

For example:

Test message, this is my product: https://example.com/products/3283284939

this becomes:

Test message, this is my product: https://example.com/products/hidden

Any ideas how could I instruct regex to ignore this when the match starts with this specific URL?

Hoped that this: /(?!https://www.example.com.*$)+?[0-9][0-9()-\s+]{6,12}[0-9]/

would work, but actually it doesn't.

0 likes
6 replies
tykus's avatar

Why complicated the regex:

$url = "https://example.com/products/3283284939";
if (!str($url)->startsWith('https://example.com/')) {
	preg_replace(/* etc */);
}
tykus's avatar

@Ninj4df

Your regex would need to be a negative lookbehind (?<!) rather than negative lookahead (?!) to match the group before the main expression. The problem now is the lookbehind expression cannot be variable length, so you need to given the full URL that you are expecting, e.g.

/(?<!https:\/\/example.com\/products\/)(\d{6,12})/

Now the 6-12 length digits should be captured and replaced only whenever they are not preceded by https://example.com/products/

tykus's avatar

@Ninj4df you won't be able to solve this with a single regular expression AFAIK - it is a limitation of lookbehind.

kokoshneta's avatar
Level 27

There are thousands of different ways to write phone numbers, and most of them also coincidentally match things that aren’t phone numbers.

I don’t think there is any way to use regex to “hide phone numbers”. That’s much too broad and ill-defined a concept.

Please or to participate in this conversation.