[PHP-DEV] [rfc] str_mask function

Why is this needed in php itself? Masking seems very use-case specific and would be better done inside php library with extensible modules for different types of data to mask.

Ilia Alshanetsky
Technologist, CTO, Entrepreneur
E: ilia@ilia.ws
T: @iliaa
B: http://ilia.ws

On Fri, Sep 18, 2026, 2:29 p.m. سپهر محمودی <sepehrphpr@gmail.com> wrote:

Hi everyone,

I’m officially starting my work on the ext/intl and standard string functions, and I’m very excited to share my first major proposal for PHP 8.7!

I have successfully set up my local development environment and compiler on my machine, and everything is up and running smoothly.

As part of this, I would like to propose a new native function called str_mask().

Proposal Overview

The str_mask() function is designed to securely mask portions of a string using a specified mask character. This is extremely useful for handling sensitive user data like credit card numbers, phone numbers, and tokens.

Signature:
str_mask(string $string, string $mask_char = ‘*’, int $offset = 0, ?int $length = null): string

Examples

  1. Masking a credit card (positive offset & length):
    $credit_card = ‘1234567890123456’;
    $masked_card = str_mask($credit_card, ‘*’, 4, 8);
    // Output: 1234********3456

  2. Masking a phone number (negative offset to count from the end):
    $phone_number = ‘+989123456789’;
    $masked_phone = str_mask($phone_number, ‘X’, -4);
    // Output: +9891234XXXX

You can find all the details, implementation plans, and RFC discussions here:
https://wiki.php.net/rfc/str_mask

Looking forward to hearing your feedback and thoughts!

Best regards,
Sepehr Mahmoudi

در تاریخ دوشنبه ۲۱ سپتامبر ۲۰۲۶، ۰۴:۰۴ Morgan <weedpacket@varteg.nz> نوشت:

On 2026-09-21 03:48, سپهر محمودی wrote:

Just to clarify the intent: str_mask() is designed not as domain/
business logic (like slugification), but as a low-level string
manipulation primitive—very similar to existing core primitives like
str_pad(), substr_replace(), and str_repeat().

The main reasons for considering it at the core level rather than
userland/PECL are:

  1. First-class integration with #[\SensitiveParameter] to ensure safe
    handling of sensitive/PII data in stack traces.
  2. Providing a strict, fail-closed contract natively without the
    allocation and performance overhead of composing multiple userland calls.

See, this #[\SensitiveParameter] thing is what makes it look to me like
business logic rather than low-level; it assumes that what is being
masked is - well - sensitive, according to some criterion. There might
be other reasons why someone will want to mask part of a string that
isn’t sensitive (anyone for a game of Hangman?).

It’s reasonable to apply #[\SensitiveParameter] to the $password field
of openssl_password_hash() or PDO::connect() because you are by
definition passing a sensitive value (a password) in that parameter. But
for low-level string manipulation? Strings are arbitrary sequences of
bytes and “sensitivity” is not an inherent property of such things.

Morgan


Hi Morgan,

That is a very valid and fair point.

The intention was to provide a helpful security default, but you are right: str_mask() is fundamentally a low-level string manipulation primitive, and masking is also used in non-sensitive contexts (like word games, anonymized identifiers, or formatting). Treating it as a generic string primitive without baking in domain-specific assumptions makes total sense.

I will remove the #[\SensitiveParameter] attribute from the RFC to keep the function purely general-purpose, consistent with other ext/standard string functions.

Thanks for the insightful feedback!

Best regards,
Sepehr

Hello dear Sepher.

So I have a question:

The main reasons for considering it at the core level rather than userland/PECL are:

  1. First-class integration with #[\SensitiveParameter] to ensure safe handling of sensitive/PII data in stack traces

Wasn’t the objective of the RFC to have first class integration with #[\SensitiveParameter]?

Also as you stated in that sentence, you want to injure handling of sensitive pii data in stack trades. However that’s kind of uses very uses as a very specific use case. But was he RFC first design for that kind of use case?

Because it is kind of hard to understand it, the reason of the RFC, if in the same mails you sent also you state that you are rectifying the RFC. It sounds like the RFC first is designed for a very specific kind of use, which is very niche, and apart from that it is a very dynamically designed RFC.

It just I’m the kind of lost of why is the using in the first place. If you can do it in user land perfectly. And in the case of using c, you have extensions that are not part of the main API but solves a very important problem and issue. Why is the need in the main PHP API? Because it sounds like you’re trying just to push something into the main API just for the sake of pushing it, and from each Mail the necessity of using it or it’s consideration at least gradually decreases

Kind regards,

David Maye

El 21/09/2026 11:56 سپهر محمودی sepehrphpr@gmail.com escribió:

در تاریخ دوشنبه ۲۱ سپتامبر ۲۰۲۶، ۰۴:۰۴ Morgan <weedpacket@varteg.nz> نوشت:

On 2026-09-21 03:48, سپهر محمودی wrote:

Just to clarify the intent: str_mask() is designed not as domain/
business logic (like slugification), but as a low-level string
manipulation primitive—very similar to existing core primitives like
str_pad(), substr_replace(), and str_repeat().

The main reasons for considering it at the core level rather than
userland/PECL are:

  1. First-class integration with #[\SensitiveParameter] to ensure safe
    handling of sensitive/PII data in stack traces.
  2. Providing a strict, fail-closed contract natively without the
    allocation and performance overhead of composing multiple userland calls.

See, this #[\SensitiveParameter] thing is what makes it look to me like
business logic rather than low-level; it assumes that what is being
masked is - well - sensitive, according to some criterion. There might
be other reasons why someone will want to mask part of a string that
isn’t sensitive (anyone for a game of Hangman?).

It’s reasonable to apply #[\SensitiveParameter] to the $password field
of openssl_password_hash() or PDO::connect() because you are by
definition passing a sensitive value (a password) in that parameter. But
for low-level string manipulation? Strings are arbitrary sequences of
bytes and “sensitivity” is not an inherent property of such things.

Morgan


Hi Morgan,

That is a very valid and fair point.

The intention was to provide a helpful security default, but you are right: str_mask() is fundamentally a low-level string manipulation primitive, and masking is also used in non-sensitive contexts (like word games, anonymized identifiers, or formatting). Treating it as a generic string primitive without baking in domain-specific assumptions makes total sense.

I will remove the #[\SensitiveParameter] attribute from the RFC to keep the function purely general-purpose, consistent with other ext/standard string functions.

Thanks for the insightful feedback!

Best regards,
Sepehr

در تاریخ دوشنبه ۲۱ سپتامبر ۲۰۲۶، ۰۴:۳۱ Ilia <ilia@ilia.ws> نوشت:

Why is this needed in php itself? Masking seems very use-case specific and would be better done inside php library with extensible modules for different types of data to mask.

Ilia Alshanetsky
Technologist, CTO, Entrepreneur
E: ilia@ilia.ws
T: @iliaa
B: http://ilia.ws

On Fri, Sep 18, 2026, 2:29 p.m. سپهر محمودی <sepehrphpr@gmail.com> wrote:

Hi everyone,

I’m officially starting my work on the ext/intl and standard string functions, and I’m very excited to share my first major proposal for PHP 8.7!

I have successfully set up my local development environment and compiler on my machine, and everything is up and running smoothly.

As part of this, I would like to propose a new native function called str_mask().

Proposal Overview

The str_mask() function is designed to securely mask portions of a string using a specified mask character. This is extremely useful for handling sensitive user data like credit card numbers, phone numbers, and tokens.

Signature:
str_mask(string $string, string $mask_char = ‘*’, int $offset = 0, ?int $length = null): string

Examples

  1. Masking a credit card (positive offset & length):
    $credit_card = ‘1234567890123456’;
    $masked_card = str_mask($credit_card, ‘*’, 4, 8);
    // Output: 1234********3456

  2. Masking a phone number (negative offset to count from the end):
    $phone_number = ‘+989123456789’;
    $masked_phone = str_mask($phone_number, ‘X’, -4);
    // Output: +9891234XXXX

You can find all the details, implementation plans, and RFC discussions here:
https://wiki.php.net/rfc/str_mask

Looking forward to hearing your feedback and thoughts!

Best regards,
Sepehr Mahmoudi


Hi Ilia,

Thanks for sharing your perspective.

I completely agree that high-level, schema-aware masking (such as formatting credit cards, emails, or complex data structures) belongs in userland libraries and extensible packages.

However, str_mask() is intentionally not designed to be a high-level formatter or business-logic helper. Instead, it is a low-level, positional string primitive—analogous to str_pad() or substr_replace()—that simply replaces a byte range with a repeating character without intermediate string allocations.

Userland libraries currently implement this through substr_replace($str, str_repeat(...)) or regex loops, incurring repeated string allocations and edge-case validation overhead. Having a single native primitive provides the fast, fail-safe foundation that those higher-level libraries can build upon.

Best regards,
Sepehr

Sorry from the last mail I meant Ensure, not injure. Grammatical character is on :sweat_smile:. Sorry everyone

El 21/09/2026 12:15 David Maye david.maye@seigisoft.com escribió:

Hello dear Sepher.

So I have a question:

The main reasons for considering it at the core level rather than userland/PECL are:

  1. First-class integration with #[\SensitiveParameter] to ensure safe handling of sensitive/PII data in stack traces

Wasn’t the objective of the RFC to have first class integration with #[\SensitiveParameter]?

Also as you stated in that sentence, you want to injure handling of sensitive pii data in stack trades. However that’s kind of uses very uses as a very specific use case. But was he RFC first design for that kind of use case?

Because it is kind of hard to understand it, the reason of the RFC, if in the same mails you sent also you state that you are rectifying the RFC. It sounds like the RFC first is designed for a very specific kind of use, which is very niche, and apart from that it is a very dynamically designed RFC.

It just I’m the kind of lost of why is the using in the first place. If you can do it in user land perfectly. And in the case of using c, you have extensions that are not part of the main API but solves a very important problem and issue. Why is the need in the main PHP API? Because it sounds like you’re trying just to push something into the main API just for the sake of pushing it, and from each Mail the necessity of using it or it’s consideration at least gradually decreases

Kind regards,

David Maye

El 21/09/2026 11:56 سپهر محمودی sepehrphpr@gmail.com escribió:

در تاریخ دوشنبه ۲۱ سپتامبر ۲۰۲۶، ۰۴:۰۴ Morgan <weedpacket@varteg.nz> نوشت:

On 2026-09-21 03:48, سپهر محمودی wrote:

Just to clarify the intent: str_mask() is designed not as domain/
business logic (like slugification), but as a low-level string
manipulation primitive—very similar to existing core primitives like
str_pad(), substr_replace(), and str_repeat().

The main reasons for considering it at the core level rather than
userland/PECL are:

  1. First-class integration with #[\SensitiveParameter] to ensure safe
    handling of sensitive/PII data in stack traces.
  2. Providing a strict, fail-closed contract natively without the
    allocation and performance overhead of composing multiple userland calls.

See, this #[\SensitiveParameter] thing is what makes it look to me like
business logic rather than low-level; it assumes that what is being
masked is - well - sensitive, according to some criterion. There might
be other reasons why someone will want to mask part of a string that
isn’t sensitive (anyone for a game of Hangman?).

It’s reasonable to apply #[\SensitiveParameter] to the $password field
of openssl_password_hash() or PDO::connect() because you are by
definition passing a sensitive value (a password) in that parameter. But
for low-level string manipulation? Strings are arbitrary sequences of
bytes and “sensitivity” is not an inherent property of such things.

Morgan


Hi Morgan,

That is a very valid and fair point.

The intention was to provide a helpful security default, but you are right: str_mask() is fundamentally a low-level string manipulation primitive, and masking is also used in non-sensitive contexts (like word games, anonymized identifiers, or formatting). Treating it as a generic string primitive without baking in domain-specific assumptions makes total sense.

I will remove the #[\SensitiveParameter] attribute from the RFC to keep the function purely general-purpose, consistent with other ext/standard string functions.

Thanks for the insightful feedback!

Best regards,
Sepehr

در تاریخ دوشنبه ۲۱ سپتامبر ۲۰۲۶، ۱۳:۴۹ David Maye <david.maye@seigisoft.com> نوشت:

Sorry from the last mail I meant Ensure, not injure. Grammatical character is on :sweat_smile:. Sorry everyone

El 21/09/2026 12:15 David Maye <david.maye@seigisoft.com> escribió:

Hello dear Sepher.

So I have a question:

The main reasons for considering it at the core level rather than userland/PECL are:

  1. First-class integration with #[\SensitiveParameter] to ensure safe handling of sensitive/PII data in stack traces

Wasn’t the objective of the RFC to have first class integration with #[\SensitiveParameter]?

Also as you stated in that sentence, you want to injure handling of sensitive pii data in stack trades. However that’s kind of uses very uses as a very specific use case. But was he RFC first design for that kind of use case?

Because it is kind of hard to understand it, the reason of the RFC, if in the same mails you sent also you state that you are rectifying the RFC. It sounds like the RFC first is designed for a very specific kind of use, which is very niche, and apart from that it is a very dynamically designed RFC.

It just I’m the kind of lost of why is the using in the first place. If you can do it in user land perfectly. And in the case of using c, you have extensions that are not part of the main API but solves a very important problem and issue. Why is the need in the main PHP API? Because it sounds like you’re trying just to push something into the main API just for the sake of pushing it, and from each Mail the necessity of using it or it’s consideration at least gradually decreases

Kind regards,

David


Hi David,

Thanks for bringing this up — it’s a completely fair observation.

You and Morgan are spot on. Having #[\SensitiveParameter] in the initial signature was conflating two separate concerns: a core string primitive versus the caller’s business context. Sensitivity is a property of the data being passed, not an intrinsic property of a byte-masking utility.

I have updated the RFC accordingly and removed #[\SensitiveParameter] from the proposed function signature:
https://wiki.php.net/rfc/str_mask

This keeps the RFC laser-focused on what str_mask() truly aims to be: a clean, low-level string manipulation primitive. The core justification remains unchanged:

  1. Performance & Zero Intermediate Allocations:
    In userland, achieving safe masking requires composing substr_replace() and str_repeat(), forcing intermediate allocations and buffer copying. A native C implementation operates directly within the buffer with zero intermediate overhead — which matters significantly on high-throughput paths like payload anonymization and access logging.

  2. Predictable, Fail-Closed Semantics:
    Existing userland helpers handle boundary conditions inconsistently. By introducing a native primitive that adheres strictly to PHP 8+ conventions (such as standard ValueError semantics for out-of-bounds offsets, identical to substr()), framework authors and libraries gain a single, reliable building block rather than maintaining disparate implementations.

Refining proposals based on community pushback is an essential part of this process, and stripping the attribute sharpens the focus entirely onto performance and language consistency.

Best regards,
Sepehr

Okay I have another question about the RFC in order to understand it’s well.

There is no need to use string repeat function at all. If I want five hashtags, I can just do “#####”, and everything is done :+1:.

Because I think people would add the str_repeat function if the data to mask has a very Dynamic length. But if we’re talking about phone numbers, credit cards, they all have the same predefined length in the entire world (in the case of phone numbers, some uses 10 digits instead of nine. But even this can be fixed pretty easily without additional temporary send string).

So if you do just like that, you are completely avoiding the use of intermediate zend string allocation. Just by replacing an operation with the correct mask, you get exactly the same result we’ve all needing to create a new global function. And (if I’m not wrong), if you want to implement a function called string mask, you can configure it in such way that it calls substring replace function without an additional Zend string allocation.

And thinking about Cake PHP: if they use the kind of pattern that this RFC that tries to avoid, which is the use of intermediate zend string allocation just for a temporal buffer, then a pull request for that function optimization can be done following that kind of pattern (no string repeat needed)

Because I think there is no need of very rigorous kind of testing just to check if some data will leak. No need to have that kind of safeguards prevents developers from “shooting on their foot” like in the case of developing in a language like C, just for masking that a a string.

So my question is: you should use the correct string mask, with predefined set of characters, inside the substring replace function, then you don’t need to string mask function right? Because the performance is nearly the same?

Awesome a 30ms difference for this kind of operation that appears not very often, is it worth it? Considering the use of unnecessary string repeat? What the benchmark shows if you just don’t use string replace?

Kind regards,
David Maye.

El 21/09/2026 13:27 سپهر محمودی sepehrphpr@gmail.com escribió:

در تاریخ دوشنبه ۲۱ سپتامبر ۲۰۲۶، ۱۳:۴۹ David Maye <david.maye@seigisoft.com> نوشت:

Sorry from the last mail I meant Ensure, not injure. Grammatical character is on :sweat_smile:. Sorry everyone

El 21/09/2026 12:15 David Maye <david.maye@seigisoft.com> escribió:

Hello dear Sepher.

So I have a question:

The main reasons for considering it at the core level rather than userland/PECL are:

  1. First-class integration with #[\SensitiveParameter] to ensure safe handling of sensitive/PII data in stack traces

Wasn’t the objective of the RFC to have first class integration with #[\SensitiveParameter]?

Also as you stated in that sentence, you want to injure handling of sensitive pii data in stack trades. However that’s kind of uses very uses as a very specific use case. But was he RFC first design for that kind of use case?

Because it is kind of hard to understand it, the reason of the RFC, if in the same mails you sent also you state that you are rectifying the RFC. It sounds like the RFC first is designed for a very specific kind of use, which is very niche, and apart from that it is a very dynamically designed RFC.

It just I’m the kind of lost of why is the using in the first place. If you can do it in user land perfectly. And in the case of using c, you have extensions that are not part of the main API but solves a very important problem and issue. Why is the need in the main PHP API? Because it sounds like you’re trying just to push something into the main API just for the sake of pushing it, and from each Mail the necessity of using it or it’s consideration at least gradually decreases

Kind regards,

David


Hi David,

Thanks for bringing this up — it’s a completely fair observation.

You and Morgan are spot on. Having #[\SensitiveParameter] in the initial signature was conflating two separate concerns: a core string primitive versus the caller’s business context. Sensitivity is a property of the data being passed, not an intrinsic property of a byte-masking utility.

I have updated the RFC accordingly and removed #[\SensitiveParameter] from the proposed function signature:
https://wiki.php.net/rfc/str_mask

This keeps the RFC laser-focused on what str_mask() truly aims to be: a clean, low-level string manipulation primitive. The core justification remains unchanged:

  1. Performance & Zero Intermediate Allocations:
    In userland, achieving safe masking requires composing substr_replace() and str_repeat(), forcing intermediate allocations and buffer copying. A native C implementation operates directly within the buffer with zero intermediate overhead — which matters significantly on high-throughput paths like payload anonymization and access logging.

  2. Predictable, Fail-Closed Semantics:
    Existing userland helpers handle boundary conditions inconsistently. By introducing a native primitive that adheres strictly to PHP 8+ conventions (such as standard ValueError semantics for out-of-bounds offsets, identical to substr()), framework authors and libraries gain a single, reliable building block rather than maintaining disparate implementations.

Refining proposals based on community pushback is an essential part of this process, and stripping the attribute sharpens the focus entirely onto performance and language consistency.

Best regards,
Sepehr

در تاریخ دوشنبه ۲۱ سپتامبر ۲۰۲۶، ۱۶:۴۰ David Maye <david.maye@seigisoft.com> نوشت:

Okay I have another question about the RFC in order to understand it’s well.

There is no need to use string repeat function at all. If I want five hashtags, I can just do “#####”, and everything is done :+1:.

Because I think people would add the str_repeat function if the data to mask has a very Dynamic length. But if we’re talking about phone numbers, credit cards, they all have the same predefined length in the entire world (in the case of phone numbers, some uses 10 digits instead of nine. But even this can be fixed pretty easily without additional temporary send string).

So if you do just like that, you are completely avoiding the use of intermediate zend string allocation. Just by replacing an operation with the correct mask, you get exactly the same result we’ve all needing to create a new global function. And (if I’m not wrong), if you want to implement a function called string mask, you can configure it in such way that it calls substring replace function without an additional Zend string allocation.

And thinking about Cake PHP: if they use the kind of pattern that this RFC that tries to avoid, which is the use of intermediate zend string allocation just for a temporal buffer, then a pull request for that function optimization can be done following that kind of pattern (no string repeat needed)

Because I think there is no need of very rigorous kind of testing just to check if some data will leak. No need to have that kind of safeguards prevents developers from “shooting on their foot” like in the case of developing in a language like C, just for masking that a a string.

So my question is: you should use the correct string mask, with predefined set of characters, inside the substring replace function, then you don’t need to string mask function right? Because the performance is nearly the same?

Awesome a 30ms difference for this kind of operation that appears not very often, is it worth it? Considering the use of unnecessary string repeat? What the benchmark shows if you just don’t use string replace?

Kind regards,
David Maye.


Hi David,

Thank you for bringing this up. It’s a great question, and I appreciate the perspective.

While it is technically possible to achieve masking using a combination of str_repeat and substr_replace, I believe there are a few reasons why a dedicated str_mask function is valuable for the PHP core:

  1. Performance and Intermediate Allocations: Regarding the performance difference: I’ve conducted some benchmarks comparing manual user-land implementations versus the overhead of these operations. You can find the data here: https://gist.github.com/sepehrphpr/86c4be78a3f4882dbd58f6598bb92b16.
    While a single call might seem negligible, string immutability in PHP means manual masking forces multiple intermediate zend string allocations and creates unnecessary pressure on the Garbage Collector. In high-throughput applications processing millions of strings (e.g., sanitizing logs, PII, or large database result sets), these hidden overheads accumulate rapidly. A C-level implementation bypasses this entirely.

  2. Code Clarity and Maintainability: Real-world data is rarely static (e.g., variable-length emails, different phone number formats, or varying credit card lengths). Developers currently have to calculate lengths, handle offsets, and manage concatenation manually. str_mask encapsulates this logic into a single, clean, and expressive call, significantly reducing the surface area for “off-by-one” or logic errors.

  3. “Pit of Success”: PHP’s philosophy often leans towards providing tools that guide developers toward the “pit of success.” Providing a native, optimized, and safe function ensures that developers are using a standardized implementation, rather than relying on inconsistent framework-level helpers or fragile custom code.

I’m aiming for this to be a “low-effort, high-impact” utility that prevents reinventing the wheel in every project.

Best regards,
Sepehr

Hi Sepehr

On 18.09.26 20:26, سپهر محمودی wrote:

I'm officially starting my work on the ext/intl and standard string functions, and I'm very excited to share my first major proposal for PHP 8.7!

You have been bombarding this list with almost 100 e-mails in the last two months. This is made worse by well-intentioned people trying to explain to you what's wrong with your low-effort proposals, but you continue not to listen. This mailing list is crucial to the project, it's how we communicate and make changes to the language. It's not a playground, but you're treating it as such. You need to stop here and drastically reduce the number of e-mails you send.

To avoid any vagueness: Don't start more than one 1 thread per month, don't send more than 3 e-mails per week. You can respond to multiple people in one e-mail if necessary. This is your last warning, if you fail to comply we will be forced to ban you from the list.

Ilija

در تاریخ دوشنبه ۲۱ سپتامبر ۲۰۲۶، ۱۸:۲۲ David Maye <david.maye@seigisoft.com> نوشت:

Okay there are many things that are incorrect with that benchmark.

First of all that’s not what I intended to say. What I was saying is that if I use a username function what’s the benchmark difference with using a string mask function from the C extension? And no that’s not even what I said. What I said was using just a mask constant mask wouldn’t it be the same then using a C string because there is no intermittent string allocation?

Second in The benchmark that you sent you’re using sensitive parameter attribute. I thought we didn’t consider it in the RFC, so why benchmark it?

Makes no sense. You aren’t proving your points that way.

Kind regards,

David Maye


Hi David,

Fair points, let me clarify:

  1. Constant mask: You’re right — a hardcoded “#####” needs no allocation. But that only covers static-length data. For real-world input (variable-length emails, phone numbers, card numbers), the mask length must be computed at runtime via str_repeat(), which is exactly where the intermediate allocation happens. str_mask eliminates that step.

  2. SensitiveParameter: Good catch. The attribute is pure metadata with zero runtime cost, so it has no effect on the benchmark results. I’ve removed it from the updated benchmark snippet to keep it consistent with the RFC.

Best regards,
Sepehr

Hi internals,

Dear Ilija,

I wanted to briefly reflect on the previous discussions and ensure we are on the same page. In the earlier thread, I realize I posted more frequently than appropriate, and I appreciate your guidance on keeping communication focused.

In the latest thread, I did my best to only reply directly when addressed by core contributors (including your own question), as I wanted to remain responsive and helpful. However, I completely understand the need to maintain low noise on the list and respect everyone’s time.

Since the previous function gathered too much controversy and discussion, I have decided to set it aside. In a few days, I would like to present a new function proposal.

I look up to your work and truly value your contributions to PHP. If you have any objections, concerns, or advice regarding this, I would greatly appreciate hearing your thoughts.

Best regards,
Sepehr