Hi

I have just created a PR with the implementation of six new functions which
can be used to manage suffixes and prefixes in strings. I did not actually
plan to create the PR just yet, I just wanted to add the implementation as
a sample of what I wanted to achieve and wanted to create the PR in my own
fork but somehow I managed to actually create it in the main repo.

This is the PR https://github.com/php/php-src/pull/20953

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

- If the domain includes a initial www part, remove it
- If the filename includes the .png extension, remove it
- If the URL does not include the http:// schema, add it
- If the URL is missing a trailing slash, add it
- If the URL starts with http://, change it to https://
- If the filename ends in .jpeg, change it to .jpg
- etc...

It is not too difficult to implement this functionality by using the
str_starts_with, str_ends_with and the substr functions or with
preg_replace but I think it would be good to have some functions that can
perform these operations in a single step, creating code which is simpler
to write and to understand

My proposal adds six functions:

function add_prefix(string $source, string $prefix): string
function add_suffix(string $source, string $suffix): string

Add a prefix or suffix to a string *only if the string does not yet have it*

function remove_prefix(string $source, string $prefix): string
function remove_suffix(string $source, string $suffix): string

Remove a prefix or suffix from a string if the string has it

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

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

This is my first contribution to php-src so I would be grateful for any
advice or hints :-)

Cheers

Carlos

Reply via email to