Hi

On 1/16/26 20:16, Barel wrote:
Nevertheless, the idea is that in php code many times we have to deal with
prefixes or suffixes of strings, this comes up a lot when you are dealing
with file names or urls. Some examples

From the back of my mind I seem to remember that this was previously proposed with similar use cases, since I can remember saying the same I'm saying here before:

Filenames and URLs are probably the worst possible use case for this feature, since they are “structured” strings where naively performing string operations at best just results in garbage and at worst result in security issues.

- If the domain includes a initial www part, remove it

This just seems unsafe, since you are likely making assumptions about URLs you don't own.

- If the filename includes the .png extension, remove it

basename($filename, ".png");

- If the URL does not include the http:// schema, add it

Simply adding a prefix will break URLs that already have a scheme. Use PHP 8.5's URI extension instead.

- If the URL is missing a trailing slash, add it
- If the URL starts with http://, change it to https://

URI extension.

- If the filename ends in .jpeg, change it to .jpg

Here you probably want to have more than one mapping (e.g. .htm to .html), so you would probably use a combination of `pathinfo()` and a lookup table.

function replace_prefix(string $source, string $prefix, string $replace):
string
function replace_suffix(string $source, string $suffix, string $replace):
string

Replace a prefix or suffix in a string it the string has it

This parameter order is inconsistent with both str_replace and preg_replace, which are likely the two closest existing functions we have.

Naming-wise these functions should definitely start with a `str_(pre|suf)fix_` prefix for proper grouping and autocompletion. Thus:

- str_prefix_add()
- str_prefix_remove()
- str_prefix_replace()
- str_suffix_add()
- str_suffix_remove()
- str_suffix_replace()

See also the corresponding policy: https://github.com/php/policies/blob/main/coding-standards-and-naming.rst#functions

And of course Juris correctly pointed out that 'add' is misleading, because the behavior is conditional.

I would like to know if the internals people think that the addition of
these functions would be interesting. If there is some interest I will
prepare a full RFC

For the reasons mentioned above, I don't see much value in the proposal. Personally I've rarely needed the functionality in the past and the cases where I needed it, it was a common enough operation that I could just place it in a function myself.

Best regards
Tim Düsterhus

Reply via email to